Commit 2db8b1bd by liimin

feat(duplicate-prevention): 添加防重复提交功能

- 新增防重复提交管理器,支持基于URL的请求去重
- 添加DuplicateRequestError错误类型用于处理重复请求
- 在Request类中集成防重复检查逻辑
- 更新README文档说明防重复提交功能
- 添加duplicate事件类型和处理逻辑
- 移除调试用的console.log语句
1 parent d83421bc
...@@ -8,6 +8,7 @@ ...@@ -8,6 +8,7 @@
- 🔐 **内置签名算法**:支持自动签名和自定义签名函数 - 🔐 **内置签名算法**:支持自动签名和自定义签名函数
- 🛡️ **拦截器支持**:请求和响应拦截器 - 🛡️ **拦截器支持**:请求和响应拦截器
- 🔄 **自动重试**:支持请求失败自动重试 - 🔄 **自动重试**:支持请求失败自动重试
- 🚫 **防重复提交**:内置防重复提交机制,避免用户重复点击造成的重复请求
- 📊 **错误监控**:集成Sentry错误上报 - 📊 **错误监控**:集成Sentry错误上报
- 🎯 **TypeScript支持**:完整的类型定义 - 🎯 **TypeScript支持**:完整的类型定义
- 🚀 **轻量级**:无额外依赖,体积小巧 - 🚀 **轻量级**:无额外依赖,体积小巧
...@@ -231,6 +232,12 @@ const request = new Request({ ...@@ -231,6 +232,12 @@ const request = new Request({
logout: (data, config) => { logout: (data, config) => {
console.log('logout事件触发', data, config); console.log('logout事件触发', data, config);
// 可以在这里处理登出逻辑 // 可以在这里处理登出逻辑
},
// 重复请求被阻止时触发
duplicate: (duplicateData, config) => {
console.log('duplicate事件触发', duplicateData, config);
// 可以在这里处理重复请求的逻辑,如显示提示信息
} }
} }
}); });
...@@ -247,6 +254,7 @@ request.get('/users').then(response => { ...@@ -247,6 +254,7 @@ request.get('/users').then(response => {
- `success`: 业务逻辑成功时(`code` 等于 `code_success_value`) - `success`: 业务逻辑成功时(`code` 等于 `code_success_value`)
- `error`: 业务逻辑失败时(`code` 不等于 `code_success_value` 且不是登出状态) - `error`: 业务逻辑失败时(`code` 不等于 `code_success_value` 且不是登出状态)
- `logout`: 需要登出时(`code` 或 `errId` 等于 `errId_logout_value`) - `logout`: 需要登出时(`code` 或 `errId` 等于 `errId_logout_value`)
- `duplicate`: 重复请求被阻止时(启用重复防护且检测到重复请求)
### 数组参数处理 ### 数组参数处理
...@@ -305,6 +313,95 @@ request.get('/users').then(response => { ...@@ -305,6 +313,95 @@ request.get('/users').then(response => {
}); });
``` ```
### 防重复提交
glsk-toolkit 内置了防重复提交机制,可以有效防止用户重复点击造成的重复请求:
```javascript
// 启用防重复提交(使用请求URL作为标识)
const response = await request.post('/api/submit-form', {
name: '张三',
email: 'zhangsan@example.com'
}, {
duplicatePrevention: true // 启用防重复提交
});
// 禁用防重复提交
const response = await request.post('/api/submit-form', {
name: '张三',
email: 'zhangsan@example.com'
}, {
duplicatePrevention: false // 禁用防重复提交
});
```
#### 防重复提交工作原理
1. **启用防重复提交**:当 `duplicatePrevention` 设置为 `true` 时,系统会使用请求URL作为唯一标识
2. **重复检测**:如果相同URL的请求正在进行中,新的请求会被阻止并抛出 `DuplicateRequestError` 错误
3. **自动清理**:请求完成(成功或失败)后,该URL的防重复标识会被自动清除
4. **事件触发**:重复请求被阻止时会触发 `duplicate` 事件
#### 处理重复请求错误
```javascript
try {
const response = await request.post('/api/submit-form', {
name: '张三',
email: 'zhangsan@example.com'
}, {
duplicatePrevention: true
});
console.log('提交成功:', response.data);
} catch (error) {
if (error.isDuplicateError) {
console.log('请求正在进行中,请勿重复提交');
// 可以显示用户友好的提示信息
} else {
console.error('提交失败:', error.message);
}
}
```
#### 监听重复请求事件
```javascript
const request = new Request({
baseURL: 'https://api.example.com',
appId: 'your_app_id',
appSecret: 'your_app_secret',
events: {
duplicate: (url, config) => {
console.log('检测到重复请求:', url);
// 可以在这里显示用户提示,如 Toast 消息
showToast('请求正在进行中,请勿重复操作');
}
}
});
```
#### 防重复提交管理器
您也可以直接使用防重复提交管理器进行更精细的控制:
```javascript
import { duplicatePreventionManager } from 'glsk-toolkit';
// 检查是否存在重复请求
const isDuplicate = duplicatePreventionManager.checkDuplicate(true, '/api/submit-form');
// 手动注册请求
const requestPromise = fetch('/api/submit-form');
duplicatePreventionManager.registerRequest(true, '/api/submit-form', requestPromise);
// 清除所有防重复记录
duplicatePreventionManager.clearAll();
// 获取当前活跃请求数量
const activeCount = duplicatePreventionManager.getActiveRequestCount();
```
### 取消请求(简化版) ### 取消请求(简化版)
glsk-toolkit 现在支持简化版的请求取消方式,请求方法直接返回带有 `abort()` 方法的对象: glsk-toolkit 现在支持简化版的请求取消方式,请求方法直接返回带有 `abort()` 方法的对象:
...@@ -508,6 +605,7 @@ const request = new Request({ ...@@ -508,6 +605,7 @@ const request = new Request({
appSecret: '', // 应用密钥 appSecret: '', // 应用密钥
signal: AbortSignal, // 用于取消请求的信号 signal: AbortSignal, // 用于取消请求的信号
signatureFunc: Function, // 自定义签名函数 signatureFunc: Function, // 自定义签名函数
duplicatePrevention: false, // 防重复提交配置,true启用/false禁用,默认为false
response: { // 响应处理配置(推荐使用) response: { // 响应处理配置(推荐使用)
code_key: 'code', // 状态码字段名,可以是字符串或字符串数组 code_key: 'code', // 状态码字段名,可以是字符串或字符串数组
code_success_value: '0', // 成功状态码值 code_success_value: '0', // 成功状态码值
......
...@@ -122,16 +122,19 @@ ...@@ -122,16 +122,19 @@
}, },
events:{ events:{
response: (responseData, config) => { response: (responseData, config) => {
console.log('response事件触发', responseData, config); console.log('%c📥 response事件触发', 'color: #4CAF50; font-weight: bold;', responseData, config);
}, },
error: (error, config) => { error: (error, config) => {
console.log('error事件触发', error, config); console.log('%c❌ error事件触发', 'color: #F44336; font-weight: bold;', error, config);
}, },
request: (request, config) => { request: (request, config) => {
console.log('request事件触发', request, config); console.log('%c📤 request事件触发', 'color: #2196F3; font-weight: bold;', request, config);
}, },
logout: (config) => { logout: (config) => {
console.log('logout事件触发', config); console.log('%c🚪 logout事件触发', 'color: #FF9800; font-weight: bold;', config);
},
duplicate: (url, config) => {
console.log('%c🚫 duplicate事件触发', 'color: #9C27B0; font-weight: bold;', url, config);
} }
} }
}); });
...@@ -142,7 +145,7 @@ ...@@ -142,7 +145,7 @@
try { try {
// 白名单URL列表由SDK内部处理 // 白名单URL列表由SDK内部处理
// 我们只需要在请求参数中添加method参数 // 我们只需要在请求参数中添加method参数
console.log('发送请求,SDK将自动检查白名单并添加sdctag参数'); // console.log('发送请求,SDK将自动检查白名单并添加sdctag参数');
// 使用params包裹GET请求参数 // 使用params包裹GET请求参数
const result = await request.get('/test/param/test', { const result = await request.get('/test/param/test', {
...@@ -168,7 +171,7 @@ ...@@ -168,7 +171,7 @@
try { try {
// 白名单URL列表由SDK内部处理 // 白名单URL列表由SDK内部处理
// 我们只需要在请求参数中添加method参数 // 我们只需要在请求参数中添加method参数
console.log('发送请求,SDK将自动检查白名单并添加sdctag参数',request.request); // console.log('发送请求,SDK将自动检查白名单并添加sdctag参数',request.request);
// POST请求使用data传递参数(放在请求体中) // POST请求使用data传递参数(放在请求体中)
const result = await request.post('/test/param/test', const result = await request.post('/test/param/test',
...@@ -178,9 +181,11 @@ ...@@ -178,9 +181,11 @@
"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}
}, }, {
duplicatePrevention: true // 简化配置:直接传入 true
}
); );
console.log("🚀 ~ result:", result) // console.log("🚀 ~ result:", result)
resultElement.textContent = resultElement.textContent =
`请求成功 响应数据: ${JSON.stringify(result, null, 2)}`; `请求成功 响应数据: ${JSON.stringify(result, null, 2)}`;
} catch (error) { } catch (error) {
......
const http = require('http');
const fs = require('fs');
const path = require('path');
const server = http.createServer((req, res) => {
let filePath = '.' + req.url;
if (filePath === './') {
filePath = './index.html';
}
const extname = String(path.extname(filePath)).toLowerCase();
const mimeTypes = {
'.html': 'text/html',
'.js': 'text/javascript',
'.css': 'text/css',
'.json': 'application/json',
'.png': 'image/png',
'.jpg': 'image/jpg',
'.gif': 'image/gif',
'.svg': 'image/svg+xml',
'.wav': 'audio/wav',
'.mp4': 'video/mp4',
'.woff': 'application/font-woff',
'.ttf': 'application/font-ttf',
'.eot': 'application/vnd.ms-fontobject',
'.otf': 'application/font-otf',
'.wasm': 'application/wasm'
};
const contentType = mimeTypes[extname] || 'application/octet-stream';
fs.readFile(filePath, (error, content) => {
if (error) {
if (error.code === 'ENOENT') {
res.writeHead(404, { 'Content-Type': 'text/html' });
res.end('<h1>404 Not Found</h1>', 'utf-8');
} else {
res.writeHead(500);
res.end('Sorry, check with the site admin for error: ' + error.code + ' ..\n');
}
} else {
res.writeHead(200, {
'Content-Type': contentType,
'Cache-Control': 'no-cache, no-store, must-revalidate',
'Pragma': 'no-cache',
'Expires': '0'
});
res.end(content, 'utf-8');
}
});
});
const PORT = 8080;
server.listen(PORT, () => {
console.log(`Server running at http://localhost:${PORT}/`);
});
\ No newline at end of file \ No newline at end of file
...@@ -55,7 +55,6 @@ class WebAdapter extends BaseAdapter { ...@@ -55,7 +55,6 @@ class WebAdapter extends BaseAdapter {
} else { } else {
// 默认使用JSON格式 // 默认使用JSON格式
options.body = JSON.stringify(data); options.body = JSON.stringify(data);
console.log("🚀 ~ WebAdapter ~ createRequestOptions ~ options.body:", options.body)
// 设置Content-Type为application/json // 设置Content-Type为application/json
if (!headers['Content-Type']) { if (!headers['Content-Type']) {
(options.headers as Record<string, string>)['Content-Type'] = 'application/json'; (options.headers as Record<string, string>)['Content-Type'] = 'application/json';
......
import type { RequestConfig, ResponseConfig, RetryConfig } from "../types"; import type { RequestConfig, ResponseConfig, RetryConfig, DuplicatePreventionOption } from "../types";
import { generateSignature } from "../security/signature"; import { generateSignature } from "../security/signature";
/** /**
...@@ -36,6 +36,8 @@ class Defaults implements RequestConfig { ...@@ -36,6 +36,8 @@ class Defaults implements RequestConfig {
enable: boolean; enable: boolean;
address?: string; address?: string;
}; };
// 防重复提交配置
duplicatePrevention: boolean;
/** /**
* 创建默认配置实例 * 创建默认配置实例
...@@ -64,6 +66,9 @@ class Defaults implements RequestConfig { ...@@ -64,6 +66,9 @@ class Defaults implements RequestConfig {
enable: config.security?.enable ?? false, enable: config.security?.enable ?? false,
address: config.security?.address, address: config.security?.address,
}; };
// 防重复提交配置
this.duplicatePrevention = config.duplicatePrevention ?? false;
// 重试配置 // 重试配置
if (config.retry) { if (config.retry) {
...@@ -103,7 +108,7 @@ class Defaults implements RequestConfig { ...@@ -103,7 +108,7 @@ class Defaults implements RequestConfig {
// 确保response正确合并 // 确保response正确合并
response: { ...this.response, ...config.response }, response: { ...this.response, ...config.response },
// 确保retry正确合并 // 确保retry正确合并
retry: { ...this.retry, ...config.retry } retry: { ...this.retry, ...config.retry },
}); });
} }
} }
......
...@@ -21,6 +21,7 @@ import Defaults from "./defaults"; ...@@ -21,6 +21,7 @@ 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 { createAbortController } from "../utils/polyfill";
import { duplicatePreventionManager, DuplicateRequestError } from "../utils/duplicate-prevention";
interface Interceptors { interface Interceptors {
request: InterceptorManager<RequestConfig>; request: InterceptorManager<RequestConfig>;
...@@ -88,8 +89,6 @@ class Request { ...@@ -88,8 +89,6 @@ class Request {
request<T = any>( request<T = any>(
options: RequestConfig = {} options: RequestConfig = {}
): Promise<ResponseData<T>> & { abort?: () => void } { ): Promise<ResponseData<T>> & { abort?: () => void } {
console.log("🚀 ~ Request ~ request ~ options:", options);
// 合并配置 // 合并配置
const config = this.defaults.merge(options); const config = this.defaults.merge(options);
...@@ -150,29 +149,34 @@ class Request { ...@@ -150,29 +149,34 @@ class Request {
async dispatchRequest<T = any>( async dispatchRequest<T = any>(
config: RequestConfig config: RequestConfig
): Promise<ResponseData<T>> { ): Promise<ResponseData<T>> {
// 防重复提交检查
if (config.duplicatePrevention) {
const requestUrl = config.url || '';
const isDuplicate = duplicatePreventionManager.checkDuplicate(config.duplicatePrevention, requestUrl);
if (isDuplicate) {
// 触发重复请求事件
dispatchEvent("duplicate",requestUrl, config);
throw new DuplicateRequestError(
`请求正在进行中,请勿重复提交。接口: ${requestUrl}`,
requestUrl,
config
);
}
}
// 添加签名 // 添加签名
const signedConfig = await this.addSignature(config); const signedConfig = await this.addSignature(config);
// 触发request事件
try {
const eventData = {
url: signedConfig.url,
method: signedConfig.method,
params: signedConfig.params,
data: signedConfig.data,
headers: signedConfig.headers,
};
// 触发request事件 // 触发request事件
dispatchEvent("request", eventData, signedConfig); dispatchEvent("request", signedConfig.url, signedConfig);
} catch (error) {
console.error("触发request事件失败:", error);
}
// 使用预先确定的适配器,并添加重试逻辑 // 使用预先确定的适配器,并添加重试逻辑
return sendRequestWithRetry(this.adapter, signedConfig) as Promise< const requestPromise = sendRequestWithRetry(this.adapter, signedConfig) as Promise<
ResponseData<T> ResponseData<T>
>; >;
// 注册请求到防重复提交管理器
if (config.duplicatePrevention) {
duplicatePreventionManager.registerRequest(config.duplicatePrevention, config.url!, requestPromise);
}
return requestPromise;
} }
/** /**
......
...@@ -79,7 +79,7 @@ const eventBus = new PubSub(); ...@@ -79,7 +79,7 @@ const eventBus = new PubSub();
/** /**
* 事件类型定义 * 事件类型定义
*/ */
export type EventType = "logout" | "error" | "success" | "request" | "response"; export type EventType = "logout" | "error" | "success" | "request" | "response" | "duplicate";
/** /**
* 事件处理器类型定义 * 事件处理器类型定义
......
...@@ -41,6 +41,16 @@ export interface RetryConfig { ...@@ -41,6 +41,16 @@ export interface RetryConfig {
shouldResetTimeout?: boolean; // 重试时是否重置超时计时器 shouldResetTimeout?: boolean; // 重试时是否重置超时计时器
} }
/**
* 防重复提交配置
*/
/**
* 防重复提交配置类型
* - true: 启用防重复提交,使用请求URL作为标识
* - false: 禁用防重复提交
*/
export type DuplicatePreventionOption = boolean;
export interface RequestConfig { export interface RequestConfig {
url?: string; url?: string;
method?: string; method?: string;
...@@ -60,6 +70,7 @@ export interface RequestConfig { ...@@ -60,6 +70,7 @@ export interface RequestConfig {
returnAll?: boolean; // 是否返回完整响应 returnAll?: boolean; // 是否返回完整响应
sentry?: SentryConfig; // Sentry配置,包含错误上报开关、DSN和选项 sentry?: SentryConfig; // Sentry配置,包含错误上报开关、DSN和选项
security?: SecurityConfig; // 安全配置,包含白名单功能开关和地址 security?: SecurityConfig; // 安全配置,包含白名单功能开关和地址
duplicatePrevention?: DuplicatePreventionOption; // 防重复提交配置(支持简化格式)
} }
export interface SignatureOptions { export interface SignatureOptions {
......
/**
* 简化版防重复提交工具模块
* 基于用户标识的简单防重复机制
*/
import type { RequestConfig } from "../types";
/**
* 防重复提交配置接口
*/
/**
* 防重复提交配置类型
* - true: 启用防重复提交,使用请求URL作为标识
* - false: 禁用防重复提交
*/
export type DuplicatePreventionOption = boolean;
/**
* 简化版防重复提交管理器
*/
export class DuplicatePreventionManager {
private static instance: DuplicatePreventionManager;
// 存储正在进行的请求标识
private activeUserKeys = new Set<string>();
private constructor() {}
/**
* 获取单例实例
*/
public static getInstance(): DuplicatePreventionManager {
if (!DuplicatePreventionManager.instance) {
DuplicatePreventionManager.instance = new DuplicatePreventionManager();
}
return DuplicatePreventionManager.instance;
}
/**
* 检查用户标识是否重复
*/
public checkUserKeyDuplicate(userKey: string): boolean {
return this.activeUserKeys.has(userKey);
}
/**
* 注册用户标识请求
*/
public registerUserKeyRequest(userKey: string, promise: Promise<any>): void {
// 添加到活跃标识集合
this.activeUserKeys.add(userKey);
// 请求完成后自动清除标识
promise
.finally(() => {
this.activeUserKeys.delete(userKey);
});
}
/**
* 检查是否为重复请求
* @param enabled 是否启用防重复提交
* @param url 请求URL
* @returns 如果是重复请求返回true
*/
checkDuplicate(enabled: boolean, url: string): boolean {
if (!enabled) {
return false;
}
return this.activeUserKeys.has(url);
}
/**
* 注册新请求
* @param enabled 是否启用防重复提交
* @param url 请求URL
* @param promise 请求Promise
*/
public registerRequest(enabled: boolean, url: string, promise: Promise<any>): void {
if (enabled) {
this.registerUserKeyRequest(url, promise);
}
}
/**
* 手动清除指定用户标识
*/
public clearUserKey(userKey: string): boolean {
return this.activeUserKeys.delete(userKey);
}
/**
* 清除所有活跃标识
*/
public clearAll(): void {
this.activeUserKeys.clear();
}
/**
* 获取当前活跃请求数量
*/
public getActiveRequestCount(): number {
return this.activeUserKeys.size;
}
/**
* 获取所有活跃的用户标识
*/
public getActiveUserKeys(): string[] {
return Array.from(this.activeUserKeys);
}
}
/**
* 获取防重复提交管理器实例
*/
export const duplicatePreventionManager = DuplicatePreventionManager.getInstance();
/**
* 防重复提交错误类
*/
export class DuplicateRequestError extends Error {
public readonly isDuplicateError = true;
public readonly userKey: string;
public readonly originalConfig: RequestConfig;
constructor(message: string, userKey: string, config: RequestConfig) {
super(message);
this.name = 'DuplicateRequestError';
this.userKey = userKey;
this.originalConfig = config;
}
}
\ No newline at end of file \ No newline at end of file
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!