feat: 添加query功能

This commit is contained in:
2024-09-08 04:32:41 +08:00
parent 443a41110a
commit 360f6ba180
24 changed files with 6228 additions and 48 deletions

View File

@@ -1,17 +1,25 @@
type AdapterOpts = {
url: string;
headers?: Record<string, string>;
body: Record<string, any>;
body?: Record<string, any>;
timeout?: number;
};
export const adapter = async (opts: AdapterOpts) => {
const controller = new AbortController();
const signal = controller.signal;
const timeout = opts.timeout || 60000; // 默认超时时间为 60s
const timer = setTimeout(() => {
controller.abort();
}, timeout);
return fetch(opts.url, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Authorization: 'Bearer ' + localStorage.getItem('token'),
...opts.headers,
},
body: JSON.stringify(opts.body),
signal,
})
.then((response) => {
// 获取 Content-Type 头部信息
@@ -27,8 +35,12 @@ export const adapter = async (opts: AdapterOpts) => {
if (err.name === 'AbortError') {
console.log('Request timed out and was aborted');
}
console.error(err);
return {
code: 500,
};
})
.finally(() => {
clearTimeout(timer);
});
};

View File

@@ -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 };

57
src/node-adapter.ts Normal file
View File

@@ -0,0 +1,57 @@
import http from 'http';
type AdapterOpts = {
url: string;
headers?: Record<string, string>;
body?: Record<string, any>;
};
export const nodeAdapter = async (opts: AdapterOpts): Promise<any> => {
return new Promise((resolve, reject) => {
const postData = JSON.stringify(opts.body || '');
const _url = new URL(opts.url);
const { hostname, port, pathname } = _url;
const options = {
hostname: hostname,
port: port,
path: pathname || '/api/router',
method: 'POST', // Assuming it's a POST request
headers: {
'Content-Type': 'application/json',
'Content-Length': Buffer.byteLength(postData),
...opts.headers,
},
};
const req = http.request(options, (res) => {
let data = '';
// Collect data chunks
res.on('data', (chunk) => {
data += chunk;
});
// Resolve when the response is complete
res.on('end', () => {
try {
const parsedData = JSON.parse(data);
resolve(parsedData);
} catch (error) {
reject(error);
}
});
});
// Handle request errors
req.on('error', (error) => {
reject(error);
});
// Write the request body and end the request
if (opts.body) {
req.write(postData);
}
req.end();
});
};
export const adapter = nodeAdapter;