2025-05-30 21:36:12 +08:00

72 lines
1.9 KiB
TypeScript

import { adapter, DataOpts, Result } from '@kevisual/query';
type QueryResourcesOptions = {
prefix?: string;
storage?: Storage;
username?: string;
[key: string]: any;
};
export class QueryResources {
prefix: string; // root/resources
storage: Storage;
constructor(opts: QueryResourcesOptions) {
if (opts.username) {
this.prefix = `/${opts.username}/resources/`;
} else {
this.prefix = opts.prefix || '';
}
this.storage = opts.storage || localStorage;
}
setUsername(username: string) {
this.prefix = `/${username}/resources/`;
}
header(headers?: Record<string, string>, json = true): Record<string, string> {
const token = this.storage.getItem('token');
const _headers: Record<string, string> = {
'Content-Type': 'application/json',
...headers,
};
if (!json) {
delete _headers['Content-Type'];
}
if (!token) {
return _headers;
}
return {
..._headers,
Authorization: `Bearer ${token}`,
};
}
async get(data: any, opts: DataOpts): Promise<any> {
return adapter({
url: opts.url!,
method: 'GET',
body: data,
...opts,
headers: this.header(opts?.headers),
});
}
async getList(prefix: string, data?: { recursive?: boolean }, opts?: DataOpts): Promise<Result<any[]>> {
return this.get(data, {
url: `${this.prefix}${prefix}`,
body: data,
...opts,
});
}
async fetchFile(filepath: string, opts?: DataOpts): Promise<Result<any>> {
return fetch(`${this.prefix}${filepath}`, {
method: 'GET',
headers: this.header(opts?.headers, false),
}).then(async (res) => {
if (!res.ok) {
return {
code: 500,
success: false,
message: `Failed to fetch file: ${res.status} ${res.statusText}`,
} as Result<any>;
}
return { code: 200, data: await res.text(), success: true } as Result<any>;
});
}
}