web.ts
4.06 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
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
import type { RequestConfig, ResponseData } from '../../types';
import { parseHeaders } from '../utils';
import type { Adapter } from '../types';
import { BaseAdapter } from './base';
// import qs from "qs"
import { stringify } from '../../libs';
/**
* Web环境适配器实现
*/
class WebAdapter extends BaseAdapter {
/**
* 创建请求选项
* @param config 请求配置
* @param fullURL 完整URL
* @returns 请求选项
*/
protected createRequestOptions(config: RequestConfig, fullURL: string): RequestInit & { timeout?: number } {
// 使用基类方法获取基础请求选项
const baseOptions = this.createBaseRequestOptions(config);
const { method, headers, data, timeout, signal } = baseOptions;
// 创建fetch请求选项
const options: RequestInit & { timeout?: number } = {
method,
headers,
signal,
timeout
};
// 处理请求体
if (method !== 'GET' && method !== 'HEAD') {
if (data instanceof FormData ||
data instanceof URLSearchParams ||
data instanceof Blob ||
data instanceof ArrayBuffer) {
options.body = data;
} else if (typeof data === 'object' && data !== null) {
// 检查Content-Type
const contentType = headers['Content-Type'] || '';
// 如果指定了application/x-www-form-urlencoded,转换为表单数据
if (contentType.includes('application/x-www-form-urlencoded')) {
const formData = new URLSearchParams();
Object.entries(data).forEach(([key, value]) => {
if (Array.isArray(value)) {
// 处理数组参数,使用索引格式 key[0]=value, key[1]=value
value.forEach((item, index) => {
formData.append(`${key}[${index}]`, String(item));
});
} else {
formData.append(key, String(value));
}
});
options.body = formData;
} else {
// 默认使用JSON格式
options.body = JSON.stringify(data);
console.log("🚀 ~ WebAdapter ~ createRequestOptions ~ options.body:", options.body)
// 设置Content-Type为application/json
if (!headers['Content-Type']) {
(options.headers as Record<string, string>)['Content-Type'] = 'application/json';
}
}
} else if (data !== undefined) {
options.body = String(data);
}
}
return options;
}
/**
* 执行请求
* @param config 请求配置
* @param options 请求选项
* @returns Promise<Response>
*/
protected executeRequest(config: RequestConfig, options: RequestInit & { fullURL: string }): Promise<Response> {
const { fullURL, ...fetchOptions } = options;
return fetch(fullURL, fetchOptions);
}
/**
* 转换响应
* @param response 原始响应
* @param config 请求配置
* @returns Promise<ResponseData<any>>
*/
protected async transformResponse(response: Response, config: RequestConfig): Promise<ResponseData<any>> {
// 解析响应头
const headers = parseHeaders(response.headers);
// 解析响应数据
let data;
try {
// 根据响应类型处理数据
const responseType = config.responseType || 'json';
switch (responseType) {
case 'json':
data = await response.json();
break;
case 'text':
data = await response.text();
break;
case 'blob':
data = await response.blob();
break;
case 'arraybuffer':
data = await response.arrayBuffer();
break;
default:
data = await response.json();
}
} catch (e) {
// 如果解析失败,返回原始文本
data = await response.text();
}
return {
data,
status: response.status,
statusText: response.statusText,
headers,
config
};
}
}
// 创建适配器实例
const webAdapterInstance = new WebAdapter();
// 导出适配器函数
const webAdapter: Adapter = webAdapterInstance.createAdapter();
export default webAdapter;