feat: 添加response handle

This commit is contained in:
xion 2025-03-21 17:07:37 +08:00
parent 17dbc08c69
commit a488c6ec48
2 changed files with 31 additions and 17 deletions

View File

@ -1,6 +1,6 @@
{ {
"name": "@kevisual/query", "name": "@kevisual/query",
"version": "0.0.10", "version": "0.0.12",
"main": "dist/index.js", "main": "dist/index.js",
"module": "dist/index.js", "module": "dist/index.js",
"types": "dist/index.d.ts", "types": "dist/index.d.ts",

View File

@ -4,7 +4,7 @@ import { adapter } from './adapter.ts';
* @param opts * @param opts
* @returns * @returns
*/ */
type Fn = (opts: { export type Fn = (opts: {
url?: string; url?: string;
headers?: Record<string, string>; headers?: Record<string, string>;
body?: Record<string, any>; body?: Record<string, any>;
@ -42,9 +42,27 @@ export type Result<S = any> = {
showError: (fn?: () => void) => void; showError: (fn?: () => void) => void;
}; };
// 额外功能 // 额外功能
type DataOpts = Partial<QueryOpts> & { export type DataOpts = Partial<QueryOpts> & {
beforeRequest?: Fn; beforeRequest?: Fn;
afterResponse?: <S, U = S>(result: Result<S>) => Promise<U>; afterResponse?: <S, U = S>(result: Result<S>, ctx?: { req?: any; res?: any; fetch?: any }) => Promise<U>;
};
/**
* , success showError,
* success code 200
* showError success false noMsg false, showError
* @param res
*/
export const setBaseResponse = (res: Result) => {
res.success = res.code === 200;
/**
*
* @param fn
*/
res.showError = (fn?: () => void) => {
if (!res.success && !res.noMsg) {
fn?.();
}
};
}; };
/** /**
* const query = new Query(); * const query = new Query();
@ -59,7 +77,7 @@ export class Query {
adapter: typeof adapter; adapter: typeof adapter;
url: string; url: string;
beforeRequest?: Fn; beforeRequest?: Fn;
afterResponse?: (result: Result) => Promise<any>; afterResponse?: DataOpts['afterResponse'];
headers?: Record<string, string>; headers?: Record<string, string>;
timeout?: number; timeout?: number;
constructor(opts?: QueryOpts) { constructor(opts?: QueryOpts) {
@ -117,19 +135,15 @@ export class Query {
} }
return adapter(req).then(async (res) => { return adapter(req).then(async (res) => {
try { try {
res.success = res.code === 200; setBaseResponse(res);
if (afterResponse) { if (afterResponse) {
return await afterResponse(res); return await afterResponse(res, {
req,
res,
fetch: adapter,
});
} }
/**
*
* @param fn
*/
res.showError = (fn?: () => void) => {
if (!res.success && !res.noResult) {
fn?.();
}
};
return res; return res;
} catch (e) { } catch (e) {
console.error('request error', e, req); console.error('request error', e, req);
@ -153,7 +167,7 @@ export class Query {
* *
* @param fn * @param fn
*/ */
after(fn: (result: Result) => Promise<any>) { after(fn: (result: Result, req?: any) => Promise<any>) {
this.afterResponse = fn; this.afterResponse = fn;
} }
} }