Commit 0d4b3314 by liimin

feat: 重构请求适配器与响应处理逻辑

- 新增 mergeAbortSignals 工具函数用于合并多个 AbortSignal
- 重构 BaseAdapter 为更精简的基类,将逻辑下沉到 helpers
- 新增 response-helpers 和 request-helpers 集中处理通用逻辑
- 优化小程序和 UniApp 适配器复用基类方法
- 新增 abort-demo.html 演示手动中止请求
- 提升重试机制可靠性,支持外部 signal 联动
- 完善类型定义,新增 IResponseConfig 接口
- 版本号升级至 1.0.3
1 parent 03edaf12
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Abort 手动中止请求演示</title>
<style>
:root { color-scheme: light dark; }
body {
font-family: Arial, sans-serif;
max-width: 900px;
margin: 0 auto;
padding: 24px;
line-height: 1.6;
background: #f6f7f9;
}
h1 { margin: 0 0 8px; }
.subtitle { color: #666; margin-bottom: 20px; }
.card {
background: #fff;
border-radius: 10px;
padding: 16px 18px;
box-shadow: 0 2px 10px rgba(0,0,0,0.06);
margin-bottom: 16px;
}
.row { display: flex; gap: 12px; flex-wrap: wrap; align-items: center; }
button {
background: #2563eb;
color: #fff;
border: none;
padding: 10px 16px;
border-radius: 8px;
cursor: pointer;
font-size: 14px;
}
button.secondary { background: #64748b; }
button.danger { background: #dc2626; }
button:disabled { opacity: 0.6; cursor: not-allowed; }
.status {
display: inline-flex; align-items: center; gap: 8px;
padding: 6px 10px; border-radius: 6px; font-size: 13px; background: #eef2ff; color: #1e40af;
}
.status.error { background: #fee2e2; color: #991b1b; }
.status.success { background: #dcfce7; color: #14532d; }
.log { white-space: pre-wrap; word-break: break-word; background:#0b1021; color:#d1d5db; padding:12px; border-radius:8px; min-height: 120px; }
.muted { color: #6b7280; font-size: 13px; }
.kv { display:grid; grid-template-columns: 140px 1fr; gap:8px 12px; }
code { background:#f1f5f9; padding:2px 6px; border-radius:4px; }
</style>
</head>
<body>
<h1>Abort 手动中止请求演示</h1>
<div class="subtitle">演示在 Web 端使用 Request + AbortController 主动中止一个耗时请求(基于 httpbin 延迟接口)。</div>
<div class="card">
<div class="kv">
<div>请求地址</div>
<div><code>https://httpbin.org/delay/10</code>(10 秒延迟)</div>
<div>发起方式</div>
<div>通过库的 <code>Request.get</code>,传入 <code>signal</code>(BaseAdapter 会合并/联动)</div>
</div>
</div>
<div class="card">
<div class="row" style="margin-bottom:10px;">
<button id="btnStart">发起耗时请求</button>
<button id="btnAbort" class="danger" disabled>立即中止</button>
<button id="btnReset" class="secondary">重置</button>
<span id="status" class="status">空闲中</span>
</div>
<div class="muted">提示:点击“发起耗时请求”后,立刻或数秒后点击“立即中止”,应当捕获到 AbortError 或等价错误;若不中止,约 10 秒后返回成功。</div>
</div>
<div class="card">
<h3 style="margin-top:0;">日志</h3>
<div id="log" class="log"></div>
</div>
<script type="module">
import { Request } from '../dist/index.esm.js';
const request = new Request({
baseURL: 'https://httpbin.org',
timeout: 0, // 不设置库内超时,让演示专注于手动 abort(0 或不填表示不超时,依实现而定)
});
const el = {
btnStart: document.getElementById('btnStart'),
btnAbort: document.getElementById('btnAbort'),
btnReset: document.getElementById('btnReset'),
status: document.getElementById('status'),
log: document.getElementById('log')
};
let controller = null;
let running = false;
let startedAt = 0;
let timer = null;
function setStatus(text, cls = '') {
el.status.textContent = text;
el.status.className = 'status' + (cls ? ' ' + cls : '');
}
function appendLog(line) {
const ts = new Date().toISOString().substring(11, 19);
el.log.textContent += `[${ts}] ${line}\n`;
el.log.scrollTop = el.log.scrollHeight;
}
function reset() {
if (timer) { clearInterval(timer); timer = null; }
controller = null; running = false; startedAt = 0;
el.btnStart.disabled = false;
el.btnAbort.disabled = true;
setStatus('空闲中');
appendLog('--- 已重置 ---');
}
async function startRequest() {
if (running) return;
running = true;
controller = new AbortController();
startedAt = Date.now();
setStatus('请求进行中...');
el.btnStart.disabled = true;
el.btnAbort.disabled = false;
appendLog('开始请求 /delay/10');
// 展示经过时间(秒)
timer = setInterval(() => {
const s = ((Date.now() - startedAt) / 1000).toFixed(1);
setStatus(`请求进行中... 已用时 ${s}s`);
}, 200);
try {
const res = await request.get('/delay/10', {
// 关键:传入外部 AbortController.signal
signal: controller.signal,
// 演示为纯粹的手动中止,不设置 retry 等其他功能,避免干扰判断
});
clearInterval(timer); timer = null;
setStatus('请求成功', 'success');
appendLog('✓ 成功返回,示例响应字段:' + JSON.stringify({ url: res?.data?.url, origin: res?.data?.origin }));
} catch (err) {
clearInterval(timer); timer = null;
const aborted = controller?.signal?.aborted;
const name = err?.name || 'Error';
const msg = err?.message || String(err);
if (aborted || name === 'AbortError') {
setStatus('已中止(Abort)', 'error');
appendLog(`✗ 请求被中止:name=${name}, message=${msg}`);
} else {
setStatus('出错', 'error');
appendLog(`✗ 发生错误:name=${name}, message=${msg}`);
}
} finally {
// 结束态统一关闭按钮状态
el.btnStart.disabled = false;
el.btnAbort.disabled = true;
running = false;
}
}
function doAbort() {
if (!controller) return;
appendLog('发出 abort() 信号');
try { controller.abort('用户主动中止'); } catch {}
}
// 事件绑定
el.btnStart.addEventListener('click', startRequest);
el.btnAbort.addEventListener('click', doAbort);
el.btnReset.addEventListener('click', reset);
// 初始
reset();
appendLog('页面已加载,可开始演示。');
</script>
</body>
</html>
\ No newline at end of file \ No newline at end of file
...@@ -88,7 +88,7 @@ ...@@ -88,7 +88,7 @@
baseURL: 'http://192.168.3.145:9898/gsc-vcp-web-facade', baseURL: 'http://192.168.3.145:9898/gsc-vcp-web-facade',
appId: 'dj_zhixin', appId: 'dj_zhixin',
appSecret: 'c24619ed7fef02a0ae16328146bca5f97cc6493957a2137b', appSecret: 'c24619ed7fef02a0ae16328146bca5f97cc6493957a2137b',
timeout:500, timeout:5000,
sentry: { sentry: {
enable: false, enable: false,
dsn: 'https://be4fb79a912b4c34a5d1c539a1618978@sentry.glsx.com.cn/1' dsn: 'https://be4fb79a912b4c34a5d1c539a1618978@sentry.glsx.com.cn/1'
...@@ -140,10 +140,10 @@ ...@@ -140,10 +140,10 @@
"dogs":{"name":"haogou","age":1}, "dogs":{"name":"haogou","age":1},
"X-Mock":false "X-Mock":false
}, },
// retry:{ retry:{
// retries: 1, retries: 3,
// retryDelay: 1000, retryDelay: 1000,
// } }
}); });
resultElement.textContent = resultElement.textContent =
......
{ {
"name": "glsk-toolkit", "name": "glsk-toolkit",
"version": "1.0.2", "version": "1.0.3",
"description": "一个兼容Web端与小程序端的工具包,包含HTTP请求、签名算法、拦截器等功能", "description": "一个兼容Web端与小程序端的工具包,包含HTTP请求、签名算法、拦截器等功能",
"main": "dist/index.js", "main": "dist/index.js",
"module": "dist/index.esm.js", "module": "dist/index.esm.js",
......
const http = require('http');
const fs = require('fs');
const path = require('path');
const ROOT = path.resolve(__dirname);
const server = http.createServer((req, res) => {
let filePath = path.join(ROOT, req.url === '/' ? '/examples/abort-demo.html' : req.url);
const extname = String(path.extname(filePath)).toLowerCase();
const mimeTypes = {
'.html': 'text/html',
'.js': 'text/javascript',
'.css': 'text/css',
'.json': 'application/json',
'.svg': 'image/svg+xml'
};
const contentType = mimeTypes[extname] || 'application/octet-stream';
fs.readFile(filePath, (error, content) => {
if (error) {
res.writeHead(404, { 'Content-Type': 'text/html' });
res.end('<h1>404 Not Found</h1>');
} else {
res.writeHead(200, {
'Content-Type': contentType,
'Cache-Control': 'no-cache, no-store, must-revalidate',
'Pragma': 'no-cache',
'Expires': '0'
});
res.end(content);
}
});
});
const PORT = 8081;
server.listen(PORT, () => {
console.log(`Preview at http://localhost:${PORT}/examples/abort-demo.html`);
});
\ No newline at end of file \ No newline at end of file
import type { RequestConfig, ResponseData } from '../../types'; import type { Adapter } from '../types';
import type { Adapter, MiniProgramRequestOptions } from '../types';
import { BaseAdapter } from './base'; import { BaseAdapter } from './base';
/** /**
* 小程序环境适配器实现 * 小程序环境适配器实现
*/ */
class MiniProgramAdapter extends BaseAdapter { class MiniProgramAdapter extends BaseAdapter {
/** // 复用基类的 createRequestOptions / executeRequest / transformResponse
* 创建请求选项 protected getPlatformRequester(): (options: any) => { abort: () => void } {
* @param config 请求配置 return (opts: any) =>
* @param fullURL 完整URL typeof wx !== 'undefined' && typeof wx.request === 'function'
* @returns 请求选项 ? wx.request(opts)
*/ : ({ abort: () => {} } as { abort: () => void });
protected createRequestOptions(config: RequestConfig, fullURL: string): MiniProgramRequestOptions {
// 使用基类方法获取平台请求选项
return this.createPlatformRequestOptions(config, fullURL);
}
/**
* 执行请求
* @param config 请求配置
* @param options 请求选项
* @returns Promise<any>
*/
protected executeRequest(config: RequestConfig, options: MiniProgramRequestOptions): Promise<any> {
return new Promise((resolve, reject) => {
// 保存请求任务引用,用于可能的中止操作
const requestTask = wx?.request({
...options,
success: resolve,
fail: reject
}) || { abort: () => {} };
// 使用基类的方法处理信号中止
this.handleAbortSignal(requestTask, config.signal);
});
}
/**
* 转换响应
* @param response 原始响应
* @param config 请求配置
* @returns ResponseData<any> | Promise<ResponseData<any>>
*/
protected transformResponse(response: any, config: RequestConfig): ResponseData<any> | Promise<ResponseData<any>> {
return {
data: response.data,
status: response.statusCode,
statusText: '',
headers: response.header,
config
};
} }
} }
......
import type { RequestConfig, ResponseData } from '../../types'; import type { Adapter } from '../types';
import type { Adapter, UniAppRequestOptions } from '../types';
import { BaseAdapter } from './base'; import { BaseAdapter } from './base';
/** /**
* UniApp环境适配器实现 * UniApp环境适配器实现
*/ */
class UniAppAdapter extends BaseAdapter { class UniAppAdapter extends BaseAdapter {
/** // 复用基类的 createRequestOptions / executeRequest / transformResponse
* 创建请求选项 protected getPlatformRequester(): (options: any) => { abort: () => void } {
* @param config 请求配置 return (opts: any) =>
* @param fullURL 完整URL typeof uni !== 'undefined' && typeof uni.request === 'function'
* @returns 请求选项 ? uni.request(opts)
*/ : ({ abort: () => {} } as { abort: () => void });
protected createRequestOptions(config: RequestConfig, fullURL: string): UniAppRequestOptions {
// 使用基类方法获取平台请求选项
return this.createPlatformRequestOptions(config, fullURL);
}
/**
* 执行请求
* @param config 请求配置
* @param options 请求选项
* @returns Promise<any>
*/
protected executeRequest(config: RequestConfig, options: UniAppRequestOptions): Promise<any> {
return new Promise((resolve, reject) => {
// 保存请求任务引用,用于可能的中止操作
const requestTask = uni?.request({
...options,
success: resolve,
fail: reject
}) || { abort: () => {} };
// 使用基类的方法处理信号中止
this.handleAbortSignal(requestTask, config.signal);
});
}
/**
* 转换响应
* @param response 原始响应
* @param config 请求配置
* @returns ResponseData<any> | Promise<ResponseData<any>>
*/
protected transformResponse(response: any, config: RequestConfig): ResponseData<any> | Promise<ResponseData<any>> {
return {
data: response.data,
status: response.statusCode,
statusText: '',
headers: response.header,
config
};
} }
} }
......
import type { RequestConfig, ResponseData } from '../../types'; import type { RequestConfig, ResponseData } from '../../types';
import { parseHeaders } from '../utils';
import type { Adapter } from '../types'; import type { Adapter } from '../types';
import { BaseAdapter } from './base'; import { BaseAdapter } from './base';
// import qs from "qs" import { transformFetchResponse } from '../handlers/web-helpers';
import { stringify } from '../../libs'; import { createWebRequestOptions } from '../handlers/web-helpers';
/** /**
* Web环境适配器实现 * Web环境适配器实现
*/ */
class WebAdapter extends BaseAdapter { class WebAdapter extends BaseAdapter {
/** /**
* 创建请求选项 * 创建请求选项 -> 委托到 helpers
* @param config 请求配置
* @param fullURL 完整URL
* @returns 请求选项
*/ */
protected createRequestOptions(config: RequestConfig, fullURL: string): RequestInit & { timeout?: number } { protected createRequestOptions(config: RequestConfig, fullURL: string): RequestInit & { timeout?: number; fullURL?: string } {
// 使用基类方法获取基础请求选项 return createWebRequestOptions(config, fullURL);
const baseOptions = this.createBaseRequestOptions(config);
const { method, headers, data, timeout, signal } = baseOptions;
// 创建fetch请求选项
const options: RequestInit & { timeout?: number } = {
method,
headers,
signal,
timeout
};
// 处理请求体
if (method !== 'GET' && method !== 'HEAD') {
if (data instanceof FormData ||
data instanceof URLSearchParams ||
data instanceof Blob ||
data instanceof ArrayBuffer) {
options.body = data;
} else if (typeof data === 'object' && data !== null) {
// 检查Content-Type
const contentType = headers['Content-Type'] || '';
// 如果指定了application/x-www-form-urlencoded,转换为表单数据
if (contentType.includes('application/x-www-form-urlencoded')) {
const formData = new URLSearchParams();
Object.entries(data).forEach(([key, value]) => {
if (Array.isArray(value)) {
// 处理数组参数,使用索引格式 key[0]=value, key[1]=value
value.forEach((item, index) => {
formData.append(`${key}[${index}]`, String(item));
});
} else {
formData.append(key, String(value));
}
});
options.body = formData;
} else {
// 默认使用JSON格式
options.body = JSON.stringify(data);
// 设置Content-Type为application/json
if (!headers['Content-Type']) {
(options.headers as Record<string, string>)['Content-Type'] = 'application/json';
}
}
} else if (data !== undefined) {
options.body = String(data);
}
}
return options;
} }
/** /**
* 执行请求 * 执行请求
* @param config 请求配置
* @param options 请求选项
* @returns Promise<Response>
*/ */
protected executeRequest(config: RequestConfig, options: RequestInit & { fullURL: string }): Promise<Response> { protected executeRequest(_config: RequestConfig, options: RequestInit & { fullURL: string }): Promise<Response> {
const { fullURL, ...fetchOptions } = options; const { fullURL, ...fetchOptions } = options as any;
return fetch(fullURL, fetchOptions); return fetch(fullURL, fetchOptions);
} }
/** /**
* 转换响应 * 转换响应 -> 委托到 helpers 的 transformFetchResponse
* @param response 原始响应
* @param config 请求配置
* @returns Promise<ResponseData<any>>
*/ */
protected async transformResponse(response: Response, config: RequestConfig): Promise<ResponseData<any>> { protected transformResponse(response: Response, config: RequestConfig): Promise<ResponseData<any>> {
// 解析响应头 return transformFetchResponse(response, config);
const headers = parseHeaders(response.headers); }
// 解析响应数据
let data;
try {
// 根据响应类型处理数据
const responseType = config.responseType || 'json';
switch (responseType) {
case 'json':
data = await response.json();
break;
case 'text':
data = await response.text();
break;
case 'blob':
data = await response.blob();
break;
case 'arraybuffer':
data = await response.arrayBuffer();
break;
default:
data = await response.json();
}
} catch (e) {
// 如果解析失败,返回原始文本
data = await response.text();
}
return { protected getPlatformRequester(): (options: any) => { abort: () => void } {
data, // Web 适配器不使用平台请求器(直接使用 fetch 并重写了 executeRequest),此实现仅为满足类型要求
status: response.status, return (_opts: any) => ({ abort: () => {} });
statusText: response.statusText,
headers,
config
};
} }
} }
......
import { RequestError } from "../../utils/error";
import { mergeAbortSignals } from "../../utils/polyfill";
import type { RequestConfig, ResponseData } from "../../types";
import { buildURL } from "../utils";
// 将与请求相关的通用辅助逻辑集中在此,便于基类瘦身与复用
export function handleAbortSignal(
requestTask: { abort: () => void },
signal?: AbortSignal
): () => void {
if (!signal) return () => {};
if (signal.aborted) {
requestTask.abort();
return () => {};
}
const abortHandler = () => requestTask.abort();
signal.addEventListener("abort", abortHandler);
return () => signal.removeEventListener("abort", abortHandler);
}
export function createBaseRequestOptions(config: RequestConfig) {
const {
method = "GET",
headers = {},
data = {},
timeout = 5000,
signal,
} = config;
return {
method: method.toUpperCase(),
headers,
data,
timeout,
signal,
};
}
export function createPlatformRequestOptions(
config: RequestConfig,
fullURL: string
) {
const { method, headers, data, timeout } = createBaseRequestOptions(config);
return {
url: fullURL,
method: method as "GET" | "POST" | "PUT" | "DELETE",
header: headers,
timeout,
data,
};
}
export function executePlatformRequest(
config: RequestConfig,
options: any,
requester: (options: any) => { abort: () => void }
): Promise<any> {
return new Promise((resolve, reject) => {
let cleanup: () => void = () => {};
const requestTask =
requester({
...options,
success: (res: any) => {
cleanup();
resolve(res);
},
fail: (err: any) => {
cleanup();
reject(err);
},
complete: () => cleanup(),
}) || ({ abort: () => {} } as { abort: () => void });
cleanup = handleAbortSignal(requestTask, config.signal);
});
}
export function createTimeoutRace(
config: RequestConfig,
options: any,
fullURL: string,
timeout: number,
sendRequest: (
config: RequestConfig,
options: any,
fullURL: string
) => Promise<ResponseData<any>>
): Promise<ResponseData<any>> {
const controller = mergeAbortSignals(config.signal);
config.signal = controller.signal;
if (options && typeof options === "object") {
(options as any).signal = controller.signal;
}
const reqPromise = sendRequest(config, options, fullURL);
let timer: any;
const timeoutPromise = new Promise<ResponseData<any>>((_, reject) => {
timer = setTimeout(() => {
controller.abort("请求超时,超时时间:" + timeout + "ms");
reject(RequestError.createTimeoutError(config));
}, timeout);
});
return Promise.race([
reqPromise.finally(() => clearTimeout(timer)),
timeoutPromise,
]);
}
// 通用的发送请求逻辑,依赖注入具体执行/转换/校验/处理方法
export async function sendRequestGeneric(
config: RequestConfig,
options: any,
fullURL: string,
deps: {
executeRequest: (config: RequestConfig, options: any) => Promise<any>;
transformResponse: (
rawResponse: any,
config: RequestConfig
) => ResponseData<any> | Promise<ResponseData<any>>;
checkHttpStatus: (
responseData: ResponseData<any>,
config: RequestConfig
) => void;
handleResponse: (
response: ResponseData<any>,
config: RequestConfig
) => ResponseData<any>;
handleError: (
error: any,
config: RequestConfig,
signal?: AbortSignal
) => never;
}
): Promise<ResponseData<any>> {
try {
const optionsWithURL = { ...options, fullURL };
const rawResponse = await deps.executeRequest(config, optionsWithURL);
const responseData = await deps.transformResponse(rawResponse, config);
deps.checkHttpStatus(responseData, config);
return deps.handleResponse(responseData, config);
} catch (error) {
deps.handleError(error as any, config, config.signal);
}
}
// 通用的处理请求流程逻辑,负责 URL 构建、选项创建与超时竞争
export function handleRequestGeneric(
config: RequestConfig,
deps: {
createRequestOptions: (config: RequestConfig, fullURL: string) => any;
sendRequest: (
config: RequestConfig,
options: any,
fullURL: string
) => Promise<ResponseData<any>>;
}
): Promise<ResponseData<any>> {
const {
baseURL = "",
url = "",
method = "GET",
params = {},
timeout = 5000,
} = config;
const fullURL = buildURL(baseURL, url, params, method);
const options = deps.createRequestOptions(config, fullURL);
if (!timeout) {
return deps.sendRequest(config, options, fullURL);
}
return createTimeoutRace(config, options, fullURL, timeout, deps.sendRequest);
}
\ No newline at end of file \ No newline at end of file
import type { RequestConfig, ResponseData } from "../../types"; import type { RequestConfig, ResponseData } from "../../types";
import { dispatchEvent } from "../../monitoring/events"; import { dispatchEvent } from "../../monitoring/events";
import { IResponseConfig } from "../types";
// 重新导出事件相关类型和函数,保持向后兼容 // 重新导出事件相关类型和函数,保持向后兼容
export type { EventType, EventHandler } from "../../monitoring/events"; export type { EventType, EventHandler } from "../../monitoring/events";
...@@ -67,13 +68,9 @@ const createStatusHandlers = (): StatusHandler[] => [ ...@@ -67,13 +68,9 @@ const createStatusHandlers = (): StatusHandler[] => [
/** /**
* 处理响应数据,集成用户提供的响应拦截器逻辑 * 处理响应数据,集成用户提供的响应拦截器逻辑
*/ */
export function processResponse( export function processResponse({ responseData, config}: IResponseConfig): ResponseData<any> {
responseData: ResponseData<any>,
config: RequestConfig
): ResponseData<any> {
// 触发响应事件 // 触发响应事件
dispatchEvent("response", responseData, config); dispatchEvent("response", responseData, config);
const { data: res } = responseData; const { data: res } = responseData;
const { returnAll, response } = config; const { returnAll, response } = config;
...@@ -81,7 +78,6 @@ export function processResponse( ...@@ -81,7 +78,6 @@ export function processResponse(
if (!response?.code_key) { if (!response?.code_key) {
return responseData; return responseData;
} }
const { const {
code_key, code_key,
errId = "errId", errId = "errId",
......
import type { RequestConfig, ResponseData } from "../../types";
import { RequestError } from "../../utils/error";
import { processResponse } from "./response-handler";
import { handleResponseParseError } from "./error-handler";
import { IResponseConfig } from "../types";
// 默认的原始响应 -> 标准 ResponseData 转换,兼容小程序/UniApp/Web 常见字段
export function transformToResponseData(
rawResponse: any,
config: RequestConfig
): ResponseData<any> {
const data = rawResponse && (rawResponse.data ?? rawResponse.body ?? rawResponse);
const status = rawResponse?.statusCode ?? rawResponse?.status ?? 200;
const statusText = rawResponse?.statusText ?? '';
const headers = rawResponse?.header ?? rawResponse?.headers ?? {};
return { data, status, statusText, headers, config };
}
// HTTP 状态检查,统一抛出 RequestError
export function checkHttpStatus({responseData, config}: IResponseConfig): void {
if (responseData.status >= 400) {
throw new RequestError(
`HTTP ${responseData.status}: ${responseData.statusText || "Unknown Error"}`,
String(responseData.status),
config,
undefined,
responseData
);
}
}
// 对响应处理做安全封装,统一转换解析错误
export function processResponseSafely(rescfg: IResponseConfig): ResponseData<any> {
try {
return processResponse(rescfg);
} catch (error) {
throw handleResponseParseError(error, rescfg.config);
}
}
\ No newline at end of file \ No newline at end of file
import { RequestConfig, ResponseData } from "../../types";
import { parseHeaders } from "../utils";
import { createBaseRequestOptions } from "./request-helpers";
// Web: 基于基础选项构造 fetch 的 RequestInit
export function createWebRequestOptions(
config: RequestConfig,
fullURL: string
): RequestInit & { timeout?: number; fullURL?: string } {
const baseOptions = createBaseRequestOptions(config) as {
method: string;
headers: Record<string, string>;
data: any;
timeout?: number;
signal?: AbortSignal;
};
const { method, headers, data, timeout, signal } = baseOptions;
const options: RequestInit & { timeout?: number; fullURL?: string } = {
method,
headers,
signal,
timeout,
fullURL,
} as any;
if (method !== 'GET' && method !== 'HEAD') {
if (
(typeof FormData !== 'undefined' && data instanceof FormData) ||
(typeof URLSearchParams !== 'undefined' && data instanceof URLSearchParams) ||
(typeof Blob !== 'undefined' && data instanceof Blob) ||
(typeof ArrayBuffer !== 'undefined' && data instanceof ArrayBuffer)
) {
(options as any).body = data;
} else if (typeof data === 'object' && data !== null) {
const contentType = headers['Content-Type'] || headers['content-type'] || '';
if (contentType.includes('application/x-www-form-urlencoded')) {
const formData = new URLSearchParams();
Object.entries(data).forEach(([key, value]) => {
if (Array.isArray(value)) {
value.forEach((item, index) => {
formData.append(`${key}[${index}]`, String(item));
});
} else {
formData.append(key, String(value));
}
});
(options as any).body = formData;
} else {
(options as any).body = JSON.stringify(data);
if (!headers['Content-Type'] && !headers['content-type']) {
(options.headers as Record<string, string>)['Content-Type'] = 'application/json';
}
}
} else if (data !== undefined) {
(options as any).body = String(data);
}
}
return options;
}
// Web 环境:将 fetch Response 转为标准 ResponseData,并根据 responseType 解析 body
export async function transformFetchResponse(
response: Response,
config: RequestConfig
): Promise<ResponseData<any>> {
const headers = parseHeaders((response as any).headers);
let data: any;
try {
const responseType = config.responseType || 'json';
switch (responseType) {
case 'json':
data = await (response as any).json();
break;
case 'text':
data = await (response as any).text();
break;
case 'blob':
data = await (response as any).blob();
break;
case 'arraybuffer':
data = await (response as any).arrayBuffer();
break;
default:
data = await (response as any).json();
}
} catch (_e) {
try {
data = await (response as any).text();
} catch {
data = null;
}
}
return {
data,
status: (response as any).status,
statusText: (response as any).statusText,
headers,
config,
};
}
\ No newline at end of file \ No newline at end of file
...@@ -9,6 +9,7 @@ export interface MiniProgramRequestOptions { ...@@ -9,6 +9,7 @@ export interface MiniProgramRequestOptions {
data?: any; data?: any;
success?: (res: any) => void; success?: (res: any) => void;
fail?: (err: any) => void; fail?: (err: any) => void;
complete?: () => void;
} }
// uniapp请求选项接口 // uniapp请求选项接口
...@@ -20,6 +21,7 @@ export interface UniAppRequestOptions { ...@@ -20,6 +21,7 @@ export interface UniAppRequestOptions {
data?: any; data?: any;
success?: (res: any) => void; success?: (res: any) => void;
fail?: (err: any) => void; fail?: (err: any) => void;
complete?: () => void;
} }
// 小程序接口 // 小程序接口
...@@ -32,6 +34,11 @@ export interface UniApp { ...@@ -32,6 +34,11 @@ export interface UniApp {
request: (options: UniAppRequestOptions) => { abort: () => void }; request: (options: UniAppRequestOptions) => { abort: () => void };
} }
export interface IResponseConfig {
responseData: ResponseData<any>,
config: RequestConfig
}
// 声明全局变量 // 声明全局变量
declare global { declare global {
const wx: MiniProgram | undefined; const wx: MiniProgram | undefined;
......
...@@ -20,7 +20,7 @@ import Trace from "../monitoring/traces"; ...@@ -20,7 +20,7 @@ import Trace from "../monitoring/traces";
import Defaults from "./defaults"; import Defaults from "./defaults";
import { initSentry, reportNetworkError } from "../monitoring/sentry"; import { initSentry, reportNetworkError } from "../monitoring/sentry";
import { buildURL } from "../adapter/utils"; import { buildURL } from "../adapter/utils";
import { createAbortController } from "../utils/polyfill"; import { mergeAbortSignals } from "../utils/polyfill";
import { duplicatePreventionManager, DuplicateRequestError } from "../utils/duplicate-prevention"; import { duplicatePreventionManager, DuplicateRequestError } from "../utils/duplicate-prevention";
interface Interceptors { interface Interceptors {
...@@ -89,18 +89,9 @@ class Request { ...@@ -89,18 +89,9 @@ class Request {
// 合并配置 // 合并配置
const config = this.defaults.merge(options); const config = this.defaults.merge(options);
// 创建AbortController用于请求取消 // 合并/联动外部 signal,得到统一可控的 controller
const controller = createAbortController(); const controller = mergeAbortSignals(config.signal);
// 将合并后的 signal 设置到 config 中
// 如果配置中已存在signal,则需要合并处理
if (config.signal) {
// 当外部signal触发abort时,也触发内部controller的abort
config.signal.addEventListener("abort", () => {
controller.abort();
});
}
// 将controller.signal设置到config中
config.signal = controller.signal; config.signal = controller.signal;
// 构建并执行拦截器链 // 构建并执行拦截器链
......
...@@ -114,4 +114,38 @@ export function createAbortController(): AbortController { ...@@ -114,4 +114,38 @@ export function createAbortController(): AbortController {
// 确保 polyfill 已初始化 // 确保 polyfill 已初始化
initAbortControllerPolyfill(); initAbortControllerPolyfill();
return new AbortController(); return new AbortController();
}
export function mergeAbortSignals(...signals: Array<AbortSignal | undefined>): AbortController {
const controller = createAbortController();
let done = false;
const abortWith = (reason?: any) => {
if (done) return;
done = true;
try {
controller.abort(reason);
} catch {
controller.abort();
}
};
// 若已有任意 signal 已中止,则立即联动中止
for (const s of signals) {
if (s?.aborted) {
// 某些环境下 AbortSignal 可能没有 reason 字段
abortWith((s as any).reason);
break;
}
}
// 监听后续的中止事件
for (const s of signals) {
if (!s) continue;
const onAbort = () => abortWith((s as any).reason);
// 适配原生与 polyfill 的 addEventListener
(s as any).addEventListener?.("abort", onAbort);
}
return controller;
} }
\ No newline at end of file \ No newline at end of file
import { RequestConfig, ResponseData } from "../types"; import { RequestConfig, ResponseData } from "../types";
import { RequestError } from "./error"; import { RequestError } from "./error";
import { createAbortController } from "./polyfill"; import { mergeAbortSignals } from "./polyfill";
import { dispatchEvent } from "../monitoring/events"; import { dispatchEvent } from "../monitoring/events";
/** /**
...@@ -41,33 +41,29 @@ export function sendRequestWithRetry( ...@@ -41,33 +41,29 @@ export function sendRequestWithRetry(
const shouldResetTimeout = retryConfig.shouldResetTimeout ?? true; const shouldResetTimeout = retryConfig.shouldResetTimeout ?? true;
return adapter(config).catch((error: RequestError) => { return adapter(config).catch((error: RequestError) => {
// 调试信息
console.log('\x1b[36m🔍 %s\x1b[0m', '重试调试信息:', {
retryCount,
retries,
errorCode: error.code,
errorStatus: error.response?.status,
isRetryableError: isRetryableError(error)
});
// 判断是否需要重试 // 判断是否需要重试
const shouldRetry = const shouldRetry =
// 未超过最大重试次数 // 未超过最大重试次数
retryCount < retries && retryCount < retries &&
// 如果有自定义重试条件,则使用自定义条件判断,否则使用默认重试条件 // 如果有自定义重试条件,则使用自定义条件判断,否则使用默认重试条件
(retryCondition ? Boolean(retryCondition(error)) : isRetryableError(error)); (retryCondition ? Boolean(retryCondition(error)) : isRetryableError(error));
if (shouldRetry) { if (shouldRetry) {
console.log('\x1b[33m🔄 %s\x1b[0m', `请求失败,正在进行第${retryCount + 1}次重试...`); console.log('\x1b[33m🔄 %s\x1b[0m', `请求失败,正在进行第${retryCount + 1}次重试...重试调试信息:`,{
retryCount,
retries,
errorCode: error.code,
errorStatus: error.response?.status,
isRetryableError: isRetryableError(error)
});
// 创建延迟Promise // 创建延迟Promise
const delayPromise = new Promise((resolve) => { const delayPromise = new Promise((resolve) => {
setTimeout(resolve, retryDelay); setTimeout(resolve, retryDelay);
}); });
// 延迟后重试 // 延迟后重试
return delayPromise.then(() => { return delayPromise.then(() => {
// 如果需要重置超时,则重新创建一个新的AbortController
if (shouldResetTimeout && config.timeout) { if (shouldResetTimeout && config.timeout) {
const controller = createAbortController(); // 重置超时时,生成新的可取消 signal,并联动外部 cancel
const controller = mergeAbortSignals(config.signal);
config.signal = controller.signal; config.signal = controller.signal;
} }
return sendRequestWithRetry(adapter, config, retryCount + 1); return sendRequestWithRetry(adapter, config, retryCount + 1);
......
...@@ -3,7 +3,7 @@ ...@@ -3,7 +3,7 @@
"target": "ES2015", "target": "ES2015",
"module": "ES2015", "module": "ES2015",
"moduleResolution": "node", "moduleResolution": "node",
"ignoreDeprecations": "6.0", "ignoreDeprecations": "5.0",
"declaration": true, "declaration": true,
"outDir": "./dist", "outDir": "./dist",
"strict": true, "strict": true,
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!