From a488c6ec486895ecce97101895d50927cd21a901 Mon Sep 17 00:00:00 2001 From: xion Date: Fri, 21 Mar 2025 17:07:37 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20=E6=B7=BB=E5=8A=A0response=20handle?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- package.json | 2 +- src/query.ts | 46 ++++++++++++++++++++++++++++++---------------- 2 files changed, 31 insertions(+), 17 deletions(-) diff --git a/package.json b/package.json index bda5655..750560d 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@kevisual/query", - "version": "0.0.10", + "version": "0.0.12", "main": "dist/index.js", "module": "dist/index.js", "types": "dist/index.d.ts", diff --git a/src/query.ts b/src/query.ts index c4accef..5ab2c13 100644 --- a/src/query.ts +++ b/src/query.ts @@ -4,7 +4,7 @@ import { adapter } from './adapter.ts'; * @param opts 请求配置 * @returns 请求配置 */ -type Fn = (opts: { +export type Fn = (opts: { url?: string; headers?: Record; body?: Record; @@ -42,9 +42,27 @@ export type Result = { showError: (fn?: () => void) => void; }; // 额外功能 -type DataOpts = Partial & { +export type DataOpts = Partial & { beforeRequest?: Fn; - afterResponse?: (result: Result) => Promise; + afterResponse?: (result: Result, ctx?: { req?: any; res?: any; fetch?: any }) => Promise; +}; +/** + * 设置基础响应, 设置 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(); @@ -59,7 +77,7 @@ export class Query { adapter: typeof adapter; url: string; beforeRequest?: Fn; - afterResponse?: (result: Result) => Promise; + afterResponse?: DataOpts['afterResponse']; headers?: Record; timeout?: number; constructor(opts?: QueryOpts) { @@ -117,19 +135,15 @@ export class Query { } return adapter(req).then(async (res) => { try { - res.success = res.code === 200; + setBaseResponse(res); 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; } catch (e) { console.error('request error', e, req); @@ -153,7 +167,7 @@ export class Query { * 请求后处理,设置请求后处理函数 * @param fn 处理函数 */ - after(fn: (result: Result) => Promise) { + after(fn: (result: Result, req?: any) => Promise) { this.afterResponse = fn; } }