From dcab87c77a167b25cbb3e10c3fb993e686a87ff2 Mon Sep 17 00:00:00 2001 From: xion Date: Fri, 21 Mar 2025 20:00:09 +0800 Subject: [PATCH] update: stop --- package.json | 2 +- src/query.ts | 29 ++++++++++++++++++++++++++++- 2 files changed, 29 insertions(+), 2 deletions(-) diff --git a/package.json b/package.json index 750560d..cb991ad 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@kevisual/query", - "version": "0.0.12", + "version": "0.0.13", "main": "dist/index.js", "module": "dist/index.js", "types": "dist/index.d.ts", diff --git a/src/query.ts b/src/query.ts index 5ab2c13..ae4fa3c 100644 --- a/src/query.ts +++ b/src/query.ts @@ -44,7 +44,7 @@ export type Result = { // 额外功能 export type DataOpts = Partial & { beforeRequest?: Fn; - afterResponse?: (result: Result, ctx?: { req?: any; res?: any; fetch?: any }) => Promise; + afterResponse?: (result: Result, ctx?: { req?: any; res?: any; fetch?: any }) => Promise; }; /** * 设置基础响应, 设置 success 和 showError, @@ -80,6 +80,11 @@ export class Query { afterResponse?: DataOpts['afterResponse']; headers?: Record; timeout?: number; + /** + * 需要突然停止请求,比如401的时候 + */ + stop?: boolean; + constructor(opts?: QueryOpts) { this.adapter = opts?.adapter || adapter; this.url = opts?.url || '/api/router'; @@ -88,6 +93,12 @@ export class Query { }; this.timeout = opts?.timeout || 60000 * 3; // 默认超时时间为 60s * 3 } + /** + * 突然停止请求 + */ + setStop(stop: boolean) { + this.stop = stop; + } /** * 发送 get 请求,转到 post 请求 * T是请求类型自定义 @@ -133,6 +144,22 @@ export class Query { showError: () => {}, }; } + if (this.stop) { + const that = this; + await new Promise((resolve) => { + let timer = 0; + const detect = setInterval(() => { + if (!that.stop) { + clearInterval(detect); + resolve(true); + } + timer++; + if (timer > 30) { + console.error('request stop: timeout', req.url, timer); + } + }, 1000); + }); + } return adapter(req).then(async (res) => { try { setBaseResponse(res);