This commit is contained in:
2024-09-07 03:43:42 +08:00
commit 443a41110a
6 changed files with 132 additions and 0 deletions

34
src/adapter.ts Normal file
View File

@@ -0,0 +1,34 @@
type AdapterOpts = {
url: string;
headers?: Record<string, string>;
body: Record<string, any>;
};
export const adapter = async (opts: AdapterOpts) => {
return fetch(opts.url, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Authorization: 'Bearer ' + localStorage.getItem('token'),
...opts.headers,
},
body: JSON.stringify(opts.body),
})
.then((response) => {
// 获取 Content-Type 头部信息
const contentType = response.headers.get('Content-Type');
// 判断返回的数据类型
if (contentType && contentType.includes('application/json')) {
return response.json(); // 解析为 JSON
} else {
return response.text(); // 解析为文本
}
})
.catch((err) => {
if (err.name === 'AbortError') {
console.log('Request timed out and was aborted');
}
return {
code: 500,
};
});
};

37
src/index.ts Normal file
View File

@@ -0,0 +1,37 @@
import { adapter } from './adapter';
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;
};
export class Query {
adapter: typeof adapter;
url: string;
beforeRequest?: Fn;
headers = {
'Content-Type': 'application/json',
Authorization: 'Bearer ' + localStorage.getItem('token'),
};
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,
};
if (this.beforeRequest) {
await this.beforeRequest(req);
}
return this.adapter(req);
}
before(fn: Fn) {
this.beforeRequest = fn;
}
}