Commit 77f17fde by liimin

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

- 将重试配置合并为 retry 对象
- 移除 httpOptions 配置,改用 response 和 retry 配置
- 重构响应处理器,使用策略模式处理不同状态
- 更新文档和示例以反映新的配置方式
- 删除不再使用的测试页面和代码
1 parent 6ad60020
...@@ -115,8 +115,11 @@ const globalDefaults = new Defaults({ ...@@ -115,8 +115,11 @@ const globalDefaults = new Defaults({
}, },
appId: 'your_app_id', appId: 'your_app_id',
appSecret: 'your_app_secret', appSecret: 'your_app_secret',
retry: {
retries: 2, retries: 2,
retryDelay: 500 retryDelay: 500,
shouldResetTimeout: true
}
}); });
// 创建使用全局配置的请求实例 // 创建使用全局配置的请求实例
...@@ -191,6 +194,59 @@ request.interceptors.response.use( ...@@ -191,6 +194,59 @@ request.interceptors.response.use(
); );
``` ```
### 事件监听
glsk-fetch 支持事件监听机制,可以监听请求的各个阶段:
```javascript
const request = new Request({
baseURL: 'https://api.example.com',
appId: 'your_app_id',
appSecret: 'your_app_secret',
// 事件配置
events: {
// 请求发送前触发
request: (requestData, config) => {
console.log('request事件触发', requestData, config);
},
// 收到响应时触发(无论成功或失败)
response: (responseData, config) => {
console.log('response事件触发', responseData, config);
},
// 请求成功时触发(业务状态码为成功值)
success: (data, config) => {
console.log('success事件触发', data, config);
},
// 请求失败时触发(业务状态码为失败值)
error: (errorData, config) => {
console.log('error事件触发', errorData, config);
},
// 需要登出时触发(业务状态码为登出值)
logout: (data, config) => {
console.log('logout事件触发', data, config);
// 可以在这里处理登出逻辑
}
}
});
// 发送请求时会自动触发相应的事件
request.get('/users').then(response => {
console.log(response.data);
});
```
**事件触发时机:**
- `request`: 请求发送前
- `response`: 收到响应时(无论成功失败)
- `success`: 业务逻辑成功时(`code` 等于 `code_success_value`)
- `error`: 业务逻辑失败时(`code` 不等于 `code_success_value` 且不是登出状态)
- `logout`: 需要登出时(`code` 或 `errId` 等于 `errId_logout_value`)
### 数组参数处理 ### 数组参数处理
glsk-fetch 支持发送包含数组的请求参数: glsk-fetch 支持发送包含数组的请求参数:
...@@ -314,181 +370,6 @@ request.get('/users', { ...@@ -314,181 +370,6 @@ request.get('/users', {
controller.abort(); controller.abort();
``` ```
### 响应处理器外部配置
glsk-fetch 支持通过外部配置来自定义响应数据的处理逻辑,包括状态码字段映射、数据字段提取和事件触发机制。
#### 基本配置
```javascript
import Request from 'glsk-fetch';
// 配置响应处理器
Request.defaults.httpOptions = {
customer: {
response: {
code_key: "status", // 状态码字段名
code_success_value: "200", // 成功状态码值
data_key: "result", // 数据字段名
errId: "errorId", // 错误ID字段名
errId_logout_value: "401" // 登出状态码值
}
}
};
// 发起请求
Request.get('/api/data').then(response => {
// 响应会根据配置自动处理
console.log(response);
});
```
#### 数组形式的状态码字段
支持使用数组形式的 `code_key`,系统会自动匹配响应中存在的字段:
```javascript
Request.defaults.httpOptions = {
customer: {
response: {
code_key: ["code", "status", "errorCode"], // 自动匹配存在的字段
code_success_value: "0",
data_key: "data"
}
}
};
```
#### returnAll 模式
当设置 `returnAll: true` 时,返回完整的响应数据而不仅仅是 `data_key` 指定的字段:
```javascript
Request.get('/api/data', {
returnAll: true,
httpOptions: {
customer: {
response: {
code_key: "status",
data_key: "payload"
}
}
}
}).then(response => {
// 返回完整响应数据
console.log(response);
});
```
#### 配置选项说明
| 选项 | 类型 | 默认值 | 说明 |
|------|------|--------|---------|
| `code_key` | `string \| string[]` | - | 状态码字段名,支持数组形式自动匹配 |
| `code_success_value` | `string \| number` | `"0"` | 表示成功的状态码值 |
| `data_key` | `string` | `"data"` | 数据字段名 |
| `errId` | `string` | `"errId"` | 错误ID字段名 |
| `errId_logout_value` | `string \| number` | - | 表示需要登出的状态码值 |
| `returnAll` | `boolean` | `false` | 是否返回完整响应数据 |
### 事件监听器
glsk-fetch 提供了强大的事件系统,允许你监听请求和响应的各个阶段,实现全局的状态管理和错误处理。
#### 基本使用
```javascript
import Request, { addEventListener, removeEventListener } from 'glsk-fetch';
// 监听成功事件
const unsubscribeSuccess = addEventListener('success', (data, config) => {
console.log('请求成功:', data);
console.log('请求配置:', config);
});
// 监听错误事件
const unsubscribeError = addEventListener('error', (data, config) => {
console.error('请求失败:', data);
// 可以在这里显示全局错误提示
});
// 监听登出事件
const unsubscribeLogout = addEventListener('logout', (data, config) => {
console.log('用户需要重新登录');
// 可以在这里跳转到登录页面
window.location.href = '/login';
});
// 监听所有响应事件
const unsubscribeResponse = addEventListener('response', (responseData, config) => {
console.log('收到响应:', responseData);
// 可以在这里进行全局的响应处理
});
// 取消监听
// unsubscribeSuccess();
// unsubscribeError();
```
#### 事件类型
| 事件类型 | 触发时机 | 参数说明 |
|----------|----------|----------|
| `success` | 响应状态码匹配 `code_success_value` 时 | `(data, config)` - 响应数据和请求配置 |
| `error` | 响应状态码不匹配成功值且不是登出状态时 | `(data, config)` - 响应数据和请求配置 |
| `logout` | 响应状态码匹配 `errId_logout_value` 时 | `(data, config)` - 响应数据和请求配置 |
| `response` | 收到任何响应时(无论成功或失败) | `(responseData, config)` - 完整响应数据和请求配置 |
#### 实际应用示例
```javascript
import Request, { addEventListener } from 'glsk-fetch';
// 全局错误处理
addEventListener('error', (data, config) => {
// 显示错误提示
if (data.message) {
alert(`请求失败: ${data.message}`);
}
// 记录错误日志
console.error('API Error:', {
url: config.url,
method: config.method,
error: data
});
});
// 全局登出处理
addEventListener('logout', (data, config) => {
// 清除本地存储的用户信息
localStorage.removeItem('token');
localStorage.removeItem('userInfo');
// 跳转到登录页面
window.location.href = '/login';
});
// 全局成功处理
addEventListener('success', (data, config) => {
// 可以在这里进行一些全局的成功处理
console.log('操作成功:', data);
});
// 配置响应处理器
Request.defaults.httpOptions = {
customer: {
response: {
code_key: "code",
code_success_value: "200",
data_key: "data",
errId: "errId",
errId_logout_value: "401"
}
}
};
```
### 批量请求的选择性取消 ### 批量请求的选择性取消
```javascript ```javascript
...@@ -626,18 +507,18 @@ const request = new Request({ ...@@ -626,18 +507,18 @@ const request = new Request({
appSecret: '', // 应用密钥 appSecret: '', // 应用密钥
signal: AbortSignal, // 用于取消请求的信号 signal: AbortSignal, // 用于取消请求的信号
signatureFunc: Function, // 自定义签名函数 signatureFunc: Function, // 自定义签名函数
returnAll: false, // 是否返回完整响应数据 response: { // 响应处理配置(推荐使用)
responseType: 'json', // 响应数据类型: 'json' | 'text' | 'blob' | 'arraybuffer' code_key: 'code', // 状态码字段名,可以是字符串或字符串数组
httpOptions: { // HTTP选项配置
customer: {
response: {
code_key: '', // 状态码字段名,支持字符串或数组
code_success_value: '0', // 成功状态码值 code_success_value: '0', // 成功状态码值
data_key: 'data', // 数据字段名 data_key: 'data', // 数据字段名
errId: 'errId', // 错误ID字段名 errId: 'errId', // 错误ID字段名
errId_logout_value: '' // 登出状态码值 errId_logout_value: '' // 登出错误ID值
} },
} retry: { // 重试配置(推荐使用)
retries: 0, // 最大重试次数,默认为0
retryDelay: 300, // 重试延迟时间(ms),默认为300ms
retryCondition: Function, // 重试条件函数,可自定义重试逻辑
shouldResetTimeout: true // 重试时是否重置超时计时器,默认为true
}, },
sentry: { // Sentry 错误上报配置 sentry: { // Sentry 错误上报配置
enable: false, // 是否启用Sentry错误上报 enable: false, // 是否启用Sentry错误上报
...@@ -652,31 +533,45 @@ const request = new Request({ ...@@ -652,31 +533,45 @@ const request = new Request({
} }
``` ```
### 导出函数 ### 响应处理配置
除了默认的 Request 实例外,glsk-fetch 还导出了以下函数: SDK 支持自定义响应数据的处理逻辑,通过 `response` 配置可以指定如何解析后端返回的数据结构:
```javascript ```javascript
import Request, { const request = new Request({
addEventListener, request: {
removeEventListener, baseURL: 'https://api.example.com'
processResponse, },
Defaults, response: {
Sentry, code_key: 'code', // 状态码字段名,支持字符串或字符串数组
simpleGet code_success_value: '0', // 成功状态码值
} from 'glsk-fetch'; data_key: 'data', // 数据字段名
errId: 'errId', // 错误ID字段名
// 事件监听器函数 errId_logout_value: '401' // 登出错误ID值
addEventListener(eventType, handler); // 添加事件监听器 }
removeEventListener(eventType, handler); // 移除事件监听器 });
```
// 响应处理函数
processResponse(responseData, config); // 手动处理响应数据 #### 响应处理配置说明
// 其他工具函数 - `code_key`: 指定后端返回数据中状态码的字段名,可以是字符串或字符串数组
Defaults; // 默认配置管理 - `code_success_value`: 指定表示成功的状态码值
Sentry; // Sentry 错误上报工具 - `data_key`: 指定后端返回数据中实际数据的字段名
simpleGet; // 简单的 GET 请求函数 - `errId`: 指定错误ID的字段名
- `errId_logout_value`: 指定需要登出的错误ID值
#### 示例后端响应格式
```json
{
"code": "0",
"data": {
"user": "张三",
"age": 25
},
"errId": "",
"message": "success"
}
``` ```
### 签名函数接口 ### 签名函数接口
...@@ -699,41 +594,6 @@ interface SignatureResult { ...@@ -699,41 +594,6 @@ interface SignatureResult {
function signatureFunc(options: SignatureOptions): SignatureResult; function signatureFunc(options: SignatureOptions): SignatureResult;
``` ```
## 开发和测试
### 响应处理器测试页面
项目提供了一个完整的测试页面来验证响应处理器的外部配置功能:
```bash
# 启动开发服务器
npm run dev
# 访问测试页面
http://localhost:8080/examples/response-handler-test.html
```
测试页面包含以下功能:
1. **自定义 code_key 配置测试** - 验证自定义状态码字段名的处理
2. **数组形式 code_key 配置测试** - 验证数组形式状态码字段的自动匹配
3. **登出状态码配置测试** - 验证登出状态码的识别和事件触发
4. **returnAll 模式测试** - 验证完整响应数据返回模式
5. **无配置情况测试** - 验证默认行为
6. **事件日志功能** - 实时查看 `success`、`error`、`logout`、`response` 事件的触发情况
每个测试都会显示:
- 配置参数
- 模拟响应数据
- 处理后的结果
- 触发的事件日志
这个测试页面可以帮助开发者:
- 理解响应处理器的工作原理
- 验证自定义配置的正确性
- 调试事件监听器的行为
- 学习最佳实践
## License ## License
MIT MIT
\ No newline at end of file \ No newline at end of file
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>响应处理器外部配置测试</title>
<style>
body {
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
max-width: 1200px;
margin: 0 auto;
padding: 20px;
background-color: #f5f5f5;
}
h1 {
color: #333;
text-align: center;
margin-bottom: 30px;
}
.test-section {
background: white;
border-radius: 8px;
padding: 20px;
margin-bottom: 20px;
box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}
.test-section h3 {
color: #2c3e50;
margin-top: 0;
border-bottom: 2px solid #3498db;
padding-bottom: 10px;
}
.config-display {
background: #f8f9fa;
border: 1px solid #dee2e6;
border-radius: 4px;
padding: 15px;
margin: 10px 0;
font-family: 'Courier New', monospace;
font-size: 14px;
}
button {
background: #3498db;
color: white;
border: none;
padding: 10px 20px;
border-radius: 4px;
cursor: pointer;
font-size: 14px;
margin: 5px;
}
button:hover {
background: #2980b9;
}
button:disabled {
background: #bdc3c7;
cursor: not-allowed;
}
.result {
margin-top: 15px;
padding: 15px;
border-radius: 4px;
font-family: 'Courier New', monospace;
font-size: 13px;
white-space: pre-wrap;
}
.result.success {
background: #d4edda;
border: 1px solid #c3e6cb;
color: #155724;
}
.result.error {
background: #f8d7da;
border: 1px solid #f5c6cb;
color: #721c24;
}
.result.info {
background: #d1ecf1;
border: 1px solid #bee5eb;
color: #0c5460;
}
.event-log {
background: #f8f9fa;
border: 1px solid #dee2e6;
border-radius: 4px;
padding: 10px;
max-height: 200px;
overflow-y: auto;
font-family: 'Courier New', monospace;
font-size: 12px;
}
.event-item {
margin: 2px 0;
padding: 2px 5px;
border-radius: 2px;
}
.event-success { background: #d4edda; }
.event-error { background: #f8d7da; }
.event-logout { background: #fff3cd; }
.event-response { background: #d1ecf1; }
</style>
</head>
<body>
<h1>响应处理器外部配置测试</h1>
<p>测试 response-handler.ts 中的外部配置功能,验证自定义字段映射和事件触发机制</p>
<!-- 事件日志 -->
<div class="test-section">
<h3>事件日志</h3>
<button onclick="clearEventLog()">清空日志</button>
<div id="eventLog" class="event-log"></div>
</div>
<!-- 测试1:自定义 code_key 配置 -->
<div class="test-section">
<h3>测试1:自定义 code_key 配置</h3>
<p>测试使用自定义的状态码字段名</p>
<div class="config-display">
配置:
{
httpOptions: {
customer: {
response: {
code_key: "status", // 自定义状态码字段
code_success_value: "200", // 成功状态码
data_key: "result" // 数据字段
}
}
}
}
模拟响应:
{
"status": "200",
"result": { "message": "操作成功", "id": 123 },
"timestamp": "2024-01-01T00:00:00Z"
}
</div>
<button onclick="testCustomCodeKey()">测试自定义 code_key</button>
<div id="result1" class="result" style="display: none;"></div>
</div>
<!-- 测试2:数组形式的 code_key 配置 -->
<div class="test-section">
<h3>测试2:数组形式的 code_key 配置</h3>
<p>测试使用数组形式的状态码字段名,自动匹配存在的字段</p>
<div class="config-display">
配置:
{
httpOptions: {
customer: {
response: {
code_key: ["code", "status", "errorCode"], // 数组形式,自动匹配
code_success_value: "0",
data_key: "data"
}
}
}
}
模拟响应:
{
"errorCode": "0",
"data": { "list": [1, 2, 3], "total": 3 },
"message": "查询成功"
}
</div>
<button onclick="testArrayCodeKey()">测试数组 code_key</button>
<div id="result2" class="result" style="display: none;"></div>
</div>
<!-- 测试3:登出状态码配置 -->
<div class="test-section">
<h3>测试3:登出状态码配置</h3>
<p>测试登出状态码的识别和事件触发</p>
<div class="config-display">
配置:
{
httpOptions: {
customer: {
response: {
code_key: "code",
errId: "errorId",
errId_logout_value: "401", // 登出状态码
data_key: "data"
}
}
}
}
模拟响应:
{
"code": "500",
"errorId": "401",
"data": null,
"message": "登录已过期,请重新登录"
}
</div>
<button onclick="testLogoutConfig()">测试登出配置</button>
<div id="result3" class="result" style="display: none;"></div>
</div>
<!-- 测试4:returnAll 模式 -->
<div class="test-section">
<h3>测试4:returnAll 模式</h3>
<p>测试 returnAll 模式下返回完整响应数据</p>
<div class="config-display">
配置:
{
returnAll: true, // 返回完整响应
httpOptions: {
customer: {
response: {
code_key: "status",
errId_logout_value: "401",
data_key: "payload"
}
}
}
}
模拟响应:
{
"status": "500",
"payload": { "error": "服务器错误" },
"meta": { "timestamp": "2024-01-01", "version": "1.0" }
}
</div>
<button onclick="testReturnAllMode()">测试 returnAll 模式</button>
<div id="result4" class="result" style="display: none;"></div>
</div>
<!-- 测试5:无配置情况 -->
<div class="test-section">
<h3>测试5:无配置情况</h3>
<p>测试没有提供 httpOptions 配置时的默认行为</p>
<div class="config-display">
配置:
{
// 无 httpOptions 配置
}
模拟响应:
{
"code": "200",
"data": { "message": "默认处理" },
"success": true
}
</div>
<button onclick="testNoConfig()">测试无配置</button>
<div id="result5" class="result" style="display: none;"></div>
</div>
<script type="module">
// 导入必要的模块
import { processResponse, addEventListener } from '../src/adapter/handlers/response-handler.ts';
// 将函数暴露到全局作用域
window.processResponse = processResponse;
window.addEventListener = addEventListener;
// 事件日志
let eventLog = [];
// 注册事件监听器
function setupEventListeners() {
const eventTypes = ['success', 'error', 'logout', 'response'];
eventTypes.forEach(eventType => {
addEventListener(eventType, (data, config) => {
const timestamp = new Date().toLocaleTimeString();
eventLog.push({
type: eventType,
timestamp,
data,
config: config ? { url: config.url, method: config.method } : null
});
updateEventLogDisplay();
});
});
}
// 更新事件日志显示
function updateEventLogDisplay() {
const logElement = document.getElementById('eventLog');
logElement.innerHTML = eventLog.map(log =>
`<div class="event-item event-${log.type}">
[${log.timestamp}] ${log.type.toUpperCase()}: ${JSON.stringify(log.data)}
</div>`
).join('');
logElement.scrollTop = logElement.scrollHeight;
}
// 清空事件日志
window.clearEventLog = function() {
eventLog = [];
updateEventLogDisplay();
};
// 初始化事件监听器
setupEventListeners();
console.log('✅ 响应处理器测试页面初始化完成');
</script>
<script>
// 测试函数需要在全局作用域中定义
// 测试1:自定义 code_key 配置
window.testCustomCodeKey = function() {
const resultDiv = document.getElementById('result1');
resultDiv.style.display = 'block';
resultDiv.className = 'result info';
resultDiv.textContent = '测试中...';
try {
// 模拟响应数据
const responseData = {
data: {
"status": "200",
"result": { "message": "操作成功", "id": 123 },
"timestamp": "2024-01-01T00:00:00Z"
},
status: 200,
statusText: 'OK'
};
// 配置
const config = {
url: '/api/test',
method: 'GET',
httpOptions: {
customer: {
response: {
code_key: "status",
code_success_value: "200",
data_key: "result"
}
}
}
};
// 处理响应
const result = window.processResponse(responseData, config);
resultDiv.className = 'result success';
resultDiv.textContent = `✓ 测试成功\n\n原始响应:\n${JSON.stringify(responseData.data, null, 2)}\n\n处理后结果:\n${JSON.stringify(result, null, 2)}`;
} catch (error) {
resultDiv.className = 'result error';
resultDiv.textContent = `✗ 测试失败\n错误:${error.message}\n堆栈:${error.stack}`;
}
};
// 测试2:数组形式的 code_key 配置
window.testArrayCodeKey = function() {
const resultDiv = document.getElementById('result2');
resultDiv.style.display = 'block';
resultDiv.className = 'result info';
resultDiv.textContent = '测试中...';
try {
const responseData = {
data: {
"errorCode": "0",
"data": { "list": [1, 2, 3], "total": 3 },
"message": "查询成功"
},
status: 200,
statusText: 'OK'
};
const config = {
url: '/api/list',
method: 'GET',
httpOptions: {
customer: {
response: {
code_key: ["code", "status", "errorCode"],
code_success_value: "0",
data_key: "data"
}
}
}
};
const result = window.processResponse(responseData, config);
resultDiv.className = 'result success';
resultDiv.textContent = `✓ 测试成功\n\n原始响应:\n${JSON.stringify(responseData.data, null, 2)}\n\n处理后结果:\n${JSON.stringify(result, null, 2)}\n\n说明:自动匹配到 "errorCode" 字段`;
} catch (error) {
resultDiv.className = 'result error';
resultDiv.textContent = `✗ 测试失败\n错误:${error.message}`;
}
};
// 测试3:登出状态码配置
window.testLogoutConfig = function() {
const resultDiv = document.getElementById('result3');
resultDiv.style.display = 'block';
resultDiv.className = 'result info';
resultDiv.textContent = '测试中...';
try {
const responseData = {
data: {
"code": "500",
"errorId": "401",
"data": null,
"message": "登录已过期,请重新登录"
},
status: 200,
statusText: 'OK'
};
const config = {
url: '/api/protected',
method: 'GET',
httpOptions: {
customer: {
response: {
code_key: "code",
errId: "errorId",
errId_logout_value: "401",
data_key: "data"
}
}
}
};
const result = window.processResponse(responseData, config);
resultDiv.className = 'result success';
resultDiv.textContent = `✓ 测试成功\n\n原始响应:\n${JSON.stringify(responseData.data, null, 2)}\n\n处理后结果:\n${JSON.stringify(result, null, 2)}\n\n说明:应该触发 logout 事件(检查事件日志)`;
} catch (error) {
resultDiv.className = 'result error';
resultDiv.textContent = `✗ 测试失败\n错误:${error.message}`;
}
};
// 测试4:returnAll 模式
window.testReturnAllMode = function() {
const resultDiv = document.getElementById('result4');
resultDiv.style.display = 'block';
resultDiv.className = 'result info';
resultDiv.textContent = '测试中...';
try {
const responseData = {
data: {
"status": "500",
"payload": { "error": "服务器错误" },
"meta": { "timestamp": "2024-01-01", "version": "1.0" }
},
status: 200,
statusText: 'OK'
};
const config = {
url: '/api/error',
method: 'GET',
returnAll: true,
httpOptions: {
customer: {
response: {
code_key: "status",
errId_logout_value: "401",
data_key: "payload"
}
}
}
};
const result = window.processResponse(responseData, config);
resultDiv.className = 'result success';
resultDiv.textContent = `✓ 测试成功\n\n原始响应:\n${JSON.stringify(responseData.data, null, 2)}\n\n处理后结果:\n${JSON.stringify(result, null, 2)}\n\n说明:returnAll 模式返回完整响应数据`;
} catch (error) {
resultDiv.className = 'result error';
resultDiv.textContent = `✗ 测试失败\n错误:${error.message}`;
}
};
// 测试5:无配置情况
window.testNoConfig = function() {
const resultDiv = document.getElementById('result5');
resultDiv.style.display = 'block';
resultDiv.className = 'result info';
resultDiv.textContent = '测试中...';
try {
const responseData = {
data: {
"code": "200",
"data": { "message": "默认处理" },
"success": true
},
status: 200,
statusText: 'OK'
};
const config = {
url: '/api/default',
method: 'GET'
// 无 httpOptions 配置
};
const result = window.processResponse(responseData, config);
resultDiv.className = 'result success';
resultDiv.textContent = `✓ 测试成功\n\n原始响应:\n${JSON.stringify(responseData.data, null, 2)}\n\n处理后结果:\n${JSON.stringify(result, null, 2)}\n\n说明:无配置时直接返回原始响应数据`;
} catch (error) {
resultDiv.className = 'result error';
resultDiv.textContent = `✗ 测试失败\n错误:${error.message}`;
}
};
</script>
</body>
</html>
\ No newline at end of file \ No newline at end of file
...@@ -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,直接返回原始响应 // 查找有效的状态码键
if (!code_key) { const codeKey = findValidCodeKey(code_key, res);
if (!codeKey) {
return responseData; 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 (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!