Commit 77f17fde by liimin

refactor(core): 重构请求配置和响应处理逻辑

- 将重试配置合并为 retry 对象
- 移除 httpOptions 配置,改用 response 和 retry 配置
- 重构响应处理器,使用策略模式处理不同状态
- 更新文档和示例以反映新的配置方式
- 删除不再使用的测试页面和代码
1 parent 6ad60020
...@@ -109,6 +109,27 @@ ...@@ -109,6 +109,27 @@
security: { security: {
enable: false, enable: false,
address: 'https://config-center-backend.glsx.com.cn/glsxAdmin/config?moduleUrl=glsx-common' // 自定义地址 address: 'https://config-center-backend.glsx.com.cn/glsxAdmin/config?moduleUrl=glsx-common' // 自定义地址
},
response: {
code_key: 'code', // 或者你后台实际使用的状态码字段名
code_success_value: '0',
data_key: 'data',
errId: 'errId',
errId_logout_value: '21'
},
events:{
response: (responseData, config) => {
console.log('response事件触发', responseData, config);
},
error: (error, config) => {
console.log('error事件触发', error, config);
},
request: (request, config) => {
console.log('request事件触发', request, config);
},
logout: (config) => {
console.log('logout事件触发', config);
}
} }
}); });
...@@ -147,19 +168,18 @@ ...@@ -147,19 +168,18 @@
console.log('发送请求,SDK将自动检查白名单并添加sdctag参数',request.request); console.log('发送请求,SDK将自动检查白名单并添加sdctag参数',request.request);
// POST请求使用data传递参数(放在请求体中) // POST请求使用data传递参数(放在请求体中)
const result = await request.request( { const result = await request.post('/test/param/test',
url:'/test/param/test', // 请求体数据
method:'POST', {
data: { "id": 6,
"id": 6, "objs": ["hehe", "haah"],
"objs": ["hehe", "haah"], "dogs": [{"name": "haogou", "age": 1}, {"name": "拉布拉多", "age": 2}],
"dogs": [{"name": "haogou", "age": 1}, {"name": "拉布拉多", "age": 2}], "dog": {"name": "haogou", "age": 1}
"dog": {"name": "haogou", "age": 1} },
} );
}); console.log("🚀 ~ result:", result)
resultElement.textContent = resultElement.textContent =
`请求成功:\n请求参数: ${JSON.stringify(result.config.params, null, 2)}\n\n响应数据: ${JSON.stringify(result.data, null, 2)}`; `请求成功 响应数据: ${JSON.stringify(result, null, 2)}`;
} catch (error) { } catch (error) {
resultElement.textContent = `请求失败: ${error.message}`; resultElement.textContent = `请求失败: ${error.message}`;
} }
......
import type { RequestConfig, ResponseData } from "../../types"; import type { RequestConfig, ResponseData } from "../../types";
import { createEventBus } from "../pubsub"; import { dispatchEvent } from "../../monitoring/events";
// 创建全局事件总线
const eventBus = createEventBus();
// 重新导出事件相关类型和函数,保持向后兼容
export type { EventType, EventHandler } from "../../monitoring/events";
export { addEventListener, removeEventListener } from "../../monitoring/events";
/** /**
* 事件类型定义 * 查找有效的状态码键
*/ */
export type EventType = "logout" | "error" | "success" | "request" | "response"; const findValidCodeKey = (codeKey: string | string[], data: any): string | undefined =>
Array.isArray(codeKey) ? codeKey.find(key => key in data) : codeKey;
/** /**
* 事件处理器类型定义 * 检查是否需要登出
*/ */
export type EventHandler = (data: any, config: RequestConfig) => void; const shouldLogout = (code: any, errValue: any, logoutValue: any): boolean =>
code == logoutValue || errValue == logoutValue;
/** /**
* 注册事件处理器 * 状态处理策略
* @param {EventType} eventType 事件类型
* @param {EventHandler} handler 处理函数
* @returns {Function} 取消订阅的函数
*/ */
export function addEventListener( interface StatusHandler {
eventType: EventType, condition: (context: StatusContext) => boolean;
handler: EventHandler handle: (context: StatusContext) => ResponseData<any>;
): Function {
const unsubscribe = eventBus.subscribe(eventType, handler);
return unsubscribe;
} }
/** interface StatusContext {
* 移除事件处理器 code: string;
* @param {EventType} eventType 事件类型 errValue: any;
* @param {EventHandler} handler 处理函数 successValue: string;
*/ logoutValue: string;
export function removeEventListener( isLogoutRequired: boolean;
eventType: EventType, res: any;
handler?: EventHandler responseData: ResponseData<any>;
): void { config: RequestConfig;
eventBus.unsubscribe(eventType, handler); dataKey: string;
} }
/** /**
* 触发事件 * 创建状态处理策略
* @param {EventType} eventType 事件类型
* @param {any} data 事件数据
* @param {RequestConfig} config 请求配置
*/ */
export function dispatchEvent( const createStatusHandlers = (): StatusHandler[] => [
eventType: EventType, {
data: any, condition: ({ code, successValue }) => code === successValue,
config: RequestConfig handle: ({ res, config, dataKey }) => {
): void { dispatchEvent("success", res, config);
eventBus.publish(eventType, data, config); return res[dataKey];
} }
},
{
condition: ({ code, logoutValue, isLogoutRequired }) =>
code === logoutValue || isLogoutRequired,
handle: ({ res, config, responseData, dataKey }) => {
dispatchEvent("logout", res, config);
return { ...responseData, data: res[dataKey] };
}
},
{
condition: () => true, // 默认处理器
handle: ({ res, config, responseData, dataKey }) => {
dispatchEvent("error", res, config);
return { ...responseData, data: res[dataKey] };
}
}
];
/** /**
* 处理响应数据,集成用户提供的响应拦截器逻辑 * 处理响应数据,集成用户提供的响应拦截器逻辑
* @param {ResponseData} responseData 响应数据
* @param {RequestConfig} config 请求配置
* @returns {ResponseData} 处理后的响应数据
*/ */
export function processResponse( export function processResponse(
responseData: ResponseData<any>, responseData: ResponseData<any>,
config: RequestConfig config: RequestConfig
): ResponseData<any> { ): ResponseData<any> {
// 触发响应事件,无论状态如何 // 触发响应事件
dispatchEvent("response", responseData, config); dispatchEvent("response", responseData, config);
const { data: res } = responseData; const { data: res } = responseData;
const { returnAll, httpOptions } = config; const { returnAll, response } = config;
// 如果没有提供httpOptions或不需要特殊处理,直接返回原始响应
if (!httpOptions || !httpOptions.customer) { // 早期返回条件检查
if (!response?.code_key) {
return responseData; return responseData;
} }
const { const {
response: { code_key,
code_key, errId = "errId",
errId = "errId", code_success_value = "0",
code_success_value = "0", data_key = "data",
data_key = "data", errId_logout_value,
errId_logout_value, } = response;
} = {},
} = httpOptions.customer; // 查找有效的状态码键
// 如果没有提供code_key,直接返回原始响应 const codeKey = findValidCodeKey(code_key, res);
if (!code_key) { if (!codeKey) {
return responseData; return responseData;
} }
// 查找适用的code键
let codekey = Array.isArray(code_key) const code = res[codeKey];
? code_key.find((key) => res.hasOwnProperty(key)) const errValue = res[errId];
: code_key; const isLogoutRequired = shouldLogout(code, errValue, errId_logout_value);
let code = res[codekey];
let errValue = res[errId]; // 处理完整响应返回
// 如果需要返回完整响应或不需要弹窗提示
if (returnAll) { if (returnAll) {
// 检查是否需要登出 if (isLogoutRequired) {
if (
(code && code == errId_logout_value) ||
(errValue && errValue == errId_logout_value)
) {
// 触发登出事件
dispatchEvent("logout", res, config); dispatchEvent("logout", res, config);
} }
return { ...responseData, data: res }; return { ...responseData, data: res };
} }
// 特殊的code处理 - 使用发布订阅模式 // 使用策略模式处理不同状态
const codeString = code + ""; const context: StatusContext = {
// 对于成功状态码,使用成功处理器 code: String(code),
if (codeString === code_success_value + "") { errValue,
// 触发成功事件 successValue: String(code_success_value),
dispatchEvent("success", res, config); logoutValue: String(errId_logout_value),
} isLogoutRequired,
// 对于登出状态码,使用登出处理器 res,
else if ( responseData,
codeString === errId_logout_value + "" || config,
(errValue && errValue == errId_logout_value) dataKey: data_key
) { };
// 触发登出事件
dispatchEvent("logout", res, config); const handlers = createStatusHandlers();
} const handler = handlers.find(h => h.condition(context));
// 其他情况使用默认处理器
else { return handler?.handle(context) ?? responseData;
// 触发错误事件
dispatchEvent("error", res, config);
}
// 如果没有处理器或处理器没有返回结果,则返回默认数据
return { ...responseData, data: res[data_key] };
} }
...@@ -18,7 +18,7 @@ export function getAdapter(options?: any): Adapter { ...@@ -18,7 +18,7 @@ export function getAdapter(options?: any): Adapter {
const env = detectEnvironment(); const env = detectEnvironment();
// 返回适配器函数,但不直接调用它 // 返回适配器函数,但不直接调用它
// 这样在实际请求时,适配器会接收完整的请求配置(包含httpOptions) // 这样在实际请求时,适配器会接收完整的请求配置
if (env === EnvironmentType.MINIPROGRAM) { if (env === EnvironmentType.MINIPROGRAM) {
// 小程序环境 // 小程序环境
return miniprogramAdapter; return miniprogramAdapter;
......
import type { RequestConfig, RetryConfig } from "../types"; import type { RequestConfig, ResponseConfig, RetryConfig } from "../types";
import { generateSignature } from "../security/signature"; import { generateSignature } from "../security/signature";
/** /**
...@@ -11,9 +11,7 @@ class Defaults implements RequestConfig { ...@@ -11,9 +11,7 @@ class Defaults implements RequestConfig {
appId: string; appId: string;
appSecret: string; appSecret: string;
// 重试配置 // 重试配置
retries: number; retry?: RetryConfig;
retryDelay: number;
shouldResetTimeout: boolean;
// 事件订阅配置 // 事件订阅配置
events: Record<string, Function>; events: Record<string, Function>;
// 请求相关 // 请求相关
...@@ -25,7 +23,7 @@ class Defaults implements RequestConfig { ...@@ -25,7 +23,7 @@ class Defaults implements RequestConfig {
// 其他可选配置 // 其他可选配置
params?: Record<string, any>; params?: Record<string, any>;
signatureFunc?: typeof generateSignature; signatureFunc?: typeof generateSignature;
httpOptions?: any; response?: ResponseConfig;
returnAll?: boolean; returnAll?: boolean;
// Sentry 配置 // Sentry 配置
sentry: { sentry: {
...@@ -69,9 +67,9 @@ class Defaults implements RequestConfig { ...@@ -69,9 +67,9 @@ class Defaults implements RequestConfig {
}; };
// 重试配置 // 重试配置
this.retries = config.retries ?? 0; // 默认不重试 if (config.retry) {
this.retryDelay = config.retryDelay ?? 300; // 默认重试延迟300ms this.retry = config.retry;
this.shouldResetTimeout = config.shouldResetTimeout ?? true; // 默认重试时重置超时 }
// 事件订阅配置 // 事件订阅配置
this.events = config.events || {}; this.events = config.events || {};
...@@ -79,7 +77,8 @@ class Defaults implements RequestConfig { ...@@ -79,7 +77,8 @@ class Defaults implements RequestConfig {
// 其他可选配置 // 其他可选配置
if (config.params) this.params = { ...config.params }; if (config.params) this.params = { ...config.params };
if (config.signatureFunc) this.signatureFunc = config.signatureFunc; if (config.signatureFunc) this.signatureFunc = config.signatureFunc;
if (config.httpOptions) this.httpOptions = config.httpOptions; if (config.response) this.response = config.response;
if (config.returnAll !== undefined) this.returnAll = config.returnAll;
// 合并其他用户提供的配置 // 合并其他用户提供的配置
Object.keys(config).forEach((key) => { Object.keys(config).forEach((key) => {
...@@ -102,6 +101,10 @@ class Defaults implements RequestConfig { ...@@ -102,6 +101,10 @@ class Defaults implements RequestConfig {
params: { ...this.params, ...config.params }, params: { ...this.params, ...config.params },
// 确保headers正确合并 // 确保headers正确合并
headers: { ...this.headers, ...config.headers }, headers: { ...this.headers, ...config.headers },
// 确保response正确合并
response: { ...this.response, ...config.response },
// 确保retry正确合并
retry: { ...this.retry, ...config.retry }
}); });
} }
} }
......
...@@ -58,8 +58,8 @@ class Request { ...@@ -58,8 +58,8 @@ class Request {
response: new InterceptorManager(), response: new InterceptorManager(),
}; };
// 在初始化时获取适合当前环境的适配器,并传递httpOptions参数 // 在初始化时获取适合当前环境的适配器
this.adapter = getAdapter(config.httpOptions); this.adapter = getAdapter();
// 在初始化时确定签名函数 // 在初始化时确定签名函数
this.signFunc = (function (config: RequestConfig) { this.signFunc = (function (config: RequestConfig) {
......
...@@ -3,12 +3,11 @@ import Defaults from './core/defaults'; ...@@ -3,12 +3,11 @@ import Defaults from './core/defaults';
import * as Sentry from './monitoring/sentry'; import * as Sentry from './monitoring/sentry';
import { simpleGet } from './utils/http'; import { simpleGet } from './utils/http';
import { initAbortControllerPolyfill } from './utils/polyfill'; import { initAbortControllerPolyfill } from './utils/polyfill';
import { processResponse, addEventListener, removeEventListener } from './adapter/handlers/response-handler';
// 初始化 AbortController polyfill(如果需要的话) // 初始化 AbortController polyfill(如果需要的话)
initAbortControllerPolyfill(); initAbortControllerPolyfill();
export default Request; export default Request;
export { Defaults, Sentry, simpleGet, processResponse, addEventListener, removeEventListener }; export { Defaults, Sentry, simpleGet };
export type { RequestConfig, ResponseData, RequestHeaders } from './types'; export type { RequestConfig, ResponseData, RequestHeaders } from './types';
export type { SentryOptions, ErrorReportOptions } from './monitoring/sentry'; export type { SentryOptions, ErrorReportOptions } from './monitoring/sentry';
\ No newline at end of file \ No newline at end of file
...@@ -18,6 +18,14 @@ export interface SentryConfig { ...@@ -18,6 +18,14 @@ export interface SentryConfig {
options?: Record<string, any>; // Sentry初始化选项 options?: Record<string, any>; // Sentry初始化选项
} }
export interface ResponseConfig {
code_key?: string | string[]; // 状态码字段名,可以是字符串或字符串数组
code_success_value?: string | number; // 成功状态码值
data_key?: string; // 数据字段名
errId?: string; // 错误ID字段名
errId_logout_value?: string | number; // 登出错误ID值
}
export interface RequestError extends Error { export interface RequestError extends Error {
code: string; code: string;
config: RequestConfig; config: RequestConfig;
...@@ -33,7 +41,7 @@ export interface RetryConfig { ...@@ -33,7 +41,7 @@ export interface RetryConfig {
shouldResetTimeout?: boolean; // 重试时是否重置超时计时器 shouldResetTimeout?: boolean; // 重试时是否重置超时计时器
} }
export interface RequestConfig extends RetryConfig { export interface RequestConfig {
url?: string; url?: string;
method?: string; method?: string;
baseURL?: string; baseURL?: string;
...@@ -47,7 +55,8 @@ export interface RequestConfig extends RetryConfig { ...@@ -47,7 +55,8 @@ export interface RequestConfig extends RetryConfig {
responseType?: 'json' | 'text' | 'blob' | 'arraybuffer'; // 响应数据类型 responseType?: 'json' | 'text' | 'blob' | 'arraybuffer'; // 响应数据类型
signatureFunc?: (options: SignatureOptions) => SignatureResult; // 添加自定义签名函数 signatureFunc?: (options: SignatureOptions) => SignatureResult; // 添加自定义签名函数
events?: Record<string, Function>; // 事件订阅配置 events?: Record<string, Function>; // 事件订阅配置
httpOptions?: any; // HTTP选项 response?: ResponseConfig; // 响应处理配置(推荐使用)
retry?: RetryConfig; // 重试配置
returnAll?: boolean; // 是否返回完整响应 returnAll?: boolean; // 是否返回完整响应
sentry?: SentryConfig; // Sentry配置,包含错误上报开关、DSN和选项 sentry?: SentryConfig; // Sentry配置,包含错误上报开关、DSN和选项
security?: SecurityConfig; // 安全配置,包含白名单功能开关和地址 security?: SecurityConfig; // 安全配置,包含白名单功能开关和地址
......
...@@ -49,8 +49,7 @@ export class RequestError extends Error { ...@@ -49,8 +49,7 @@ export class RequestError extends Error {
data: this.config?.data, data: this.config?.data,
headers: this.config?.headers, headers: this.config?.headers,
timeout: this.config?.timeout, timeout: this.config?.timeout,
retries: this.config?.retries, retry: this.config?.retry,
retryDelay: this.config?.retryDelay,
// 响应信息 // 响应信息
status: this.response?.status, status: this.response?.status,
......
...@@ -30,7 +30,12 @@ export function sendRequestWithRetry( ...@@ -30,7 +30,12 @@ export function sendRequestWithRetry(
config: RequestConfig, config: RequestConfig,
retryCount: number = 0 retryCount: number = 0
): Promise<ResponseData<any>> { ): Promise<ResponseData<any>> {
const { retries = 0, retryDelay = 300, retryCondition } = config; // 使用retry配置
const retryConfig = config.retry || {};
const retries = retryConfig.retries ?? 0;
const retryDelay = retryConfig.retryDelay ?? 300;
const retryCondition = retryConfig.retryCondition;
const shouldResetTimeout = retryConfig.shouldResetTimeout ?? true;
return adapter(config).catch((error: RequestError) => { return adapter(config).catch((error: RequestError) => {
// 判断是否需要重试 // 判断是否需要重试
...@@ -51,7 +56,7 @@ export function sendRequestWithRetry( ...@@ -51,7 +56,7 @@ export function sendRequestWithRetry(
// 延迟后重试 // 延迟后重试
return delayPromise.then(() => { return delayPromise.then(() => {
// 如果需要重置超时,则重新创建一个新的AbortController // 如果需要重置超时,则重新创建一个新的AbortController
if (config.shouldResetTimeout && config.timeout) { if (shouldResetTimeout && config.timeout) {
const controller = createAbortController(); const controller = createAbortController();
config.signal = controller.signal; config.signal = controller.signal;
} }
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!