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, json = true): Record { const token = this.storage.getItem('token'); const _headers: Record = { '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 { 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> { return this.get(data, { url: `${this.prefix}${prefix}`, body: data, ...opts, }); } async fetchFile(filepath: string, opts?: DataOpts): Promise> { 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; } return { code: 200, data: await res.text(), success: true } as Result; }); } }