defaults.ts
2.91 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
import type { RequestConfig, RetryConfig } from "../types";
import { generateSignature } from "../security/signature";
/**
* 请求默认配置类
*/
class Defaults implements RequestConfig {
baseURL: string;
timeout: number;
headers: Record<string, string>;
appId: string;
appSecret: string;
// 重试配置
retries: number;
retryDelay: number;
shouldResetTimeout: boolean;
// 事件订阅配置
events: Record<string, Function>;
// 请求相关
signal?: AbortSignal;
method?: string;
url?: string;
data?: any;
responseType?: "json" | "text" | "blob" | "arraybuffer";
// 其他可选配置
params?: Record<string, any>;
signatureFunc?: typeof generateSignature;
httpOptions?: any;
returnAll?: boolean;
// Sentry 配置
sentry: {
enable: boolean;
dsn?: string;
options?: Record<string, any>;
};
// 安全配置
security: {
enable: boolean;
address?: string;
};
/**
* 创建默认配置实例
* @param config 用户提供的配置
*/
constructor(config: Partial<RequestConfig> = {}) {
// 检查必填参数
if (!config.sentry?.dsn) {
throw new Error("sentry.dsn is required for initialization");
}
// 基础配置
this.baseURL = config.baseURL || "";
this.timeout = config.timeout || 5000;
this.headers = {
"Content-Type": "application/json;charset=UTF-8",
...config.headers,
};
this.appId = config.appId || "";
this.appSecret = config.appSecret || "";
this.sentry = {
enable: config.sentry?.enable ?? false,
dsn: config.sentry?.dsn,
options: config.sentry?.options || {},
};
this.security = {
enable: config.security?.enable ?? false,
address: config.security?.address,
};
// 重试配置
this.retries = config.retries ?? 0; // 默认不重试
this.retryDelay = config.retryDelay ?? 300; // 默认重试延迟300ms
this.shouldResetTimeout = config.shouldResetTimeout ?? true; // 默认重试时重置超时
// 事件订阅配置
this.events = config.events || {};
// 其他可选配置
if (config.params) this.params = { ...config.params };
if (config.signatureFunc) this.signatureFunc = config.signatureFunc;
if (config.httpOptions) this.httpOptions = config.httpOptions;
// 合并其他用户提供的配置
Object.keys(config).forEach((key) => {
if (!(key in this)) {
(this as any)[key] = (config as any)[key];
}
});
}
/**
* 创建新的配置实例,合并当前配置和新配置
* @param config 要合并的新配置
* @returns 新的配置实例
*/
merge(config: Partial<RequestConfig> = {}): Defaults {
return new Defaults({
...this,
...config,
// 确保params正确合并
params: { ...this.params, ...config.params },
// 确保headers正确合并
headers: { ...this.headers, ...config.headers },
});
}
}
export default Defaults;