Commit 77f17fde by liimin

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

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