feat: 添加query功能
This commit is contained in:
64
src/index.ts
64
src/index.ts
@@ -1,37 +1,65 @@
|
||||
import { adapter } from './adapter';
|
||||
import { adapter } from './adapter.ts';
|
||||
|
||||
type Fn = (opts: {
|
||||
url?: string;
|
||||
headers?: Record<string, string>;
|
||||
body?: Record<string, any>;
|
||||
[key: string]: any;
|
||||
timeout?: number;
|
||||
}) => Promise<Record<string, any>>;
|
||||
|
||||
type Fn = (opts: { url?: string; headers?: Record<string, string>; body?: Record<string, any>; [key: string]: any }) => Promise<Record<string, any>>;
|
||||
type QueryOpts = {
|
||||
url?: string;
|
||||
adapter?: typeof adapter;
|
||||
headers?: Record<string, string>;
|
||||
timeout?: number;
|
||||
};
|
||||
type Data = {
|
||||
path?: string;
|
||||
key?: string;
|
||||
[key: string]: any;
|
||||
};
|
||||
// 额外功能
|
||||
type DataOpts = Partial<QueryOpts> & {
|
||||
beforeRequest?: Fn;
|
||||
};
|
||||
export class Query {
|
||||
adapter: typeof adapter;
|
||||
url: string;
|
||||
beforeRequest?: Fn;
|
||||
headers = {
|
||||
'Content-Type': 'application/json',
|
||||
Authorization: 'Bearer ' + localStorage.getItem('token'),
|
||||
};
|
||||
headers?: Record<string, string>;
|
||||
timeout?: number;
|
||||
constructor(opts: QueryOpts) {
|
||||
this.adapter = opts.adapter || adapter;
|
||||
this.url = opts.url || '/api/router';
|
||||
}
|
||||
async get(params: Record<string, any>) {
|
||||
return this.post(params);
|
||||
}
|
||||
async post(body: Record<string, any>) {
|
||||
const req = {
|
||||
url: this.url,
|
||||
headers: this.headers,
|
||||
body,
|
||||
this.headers = opts.headers || {
|
||||
'Content-Type': 'application/json',
|
||||
};
|
||||
if (this.beforeRequest) {
|
||||
await this.beforeRequest(req);
|
||||
this.timeout = opts.timeout || 60000; // 默认超时时间为 60s
|
||||
}
|
||||
async get<T>(params: Record<string, any> & Data & T, options?: DataOpts) {
|
||||
return this.post(params, options);
|
||||
}
|
||||
async post<T>(body: Record<string, any> & Data & T, options?: DataOpts) {
|
||||
const url = options?.url || this.url;
|
||||
const headers = { ...this.headers, ...options?.headers };
|
||||
const adapter = options?.adapter || this.adapter;
|
||||
const beforeRequest = options?.beforeRequest || this.beforeRequest;
|
||||
const timeout = options?.timeout || this.timeout;
|
||||
const req = {
|
||||
url: url,
|
||||
headers: headers,
|
||||
body,
|
||||
timeout,
|
||||
};
|
||||
if (beforeRequest) {
|
||||
await beforeRequest(req);
|
||||
}
|
||||
return this.adapter(req);
|
||||
return adapter(req);
|
||||
}
|
||||
before(fn: Fn) {
|
||||
this.beforeRequest = fn;
|
||||
}
|
||||
}
|
||||
|
||||
export { adapter };
|
||||
|
||||
Reference in New Issue
Block a user