web-helpers.ts
3.11 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
import { RequestConfig, ResponseData } from "../../types";
import { parseHeaders } from "../utils";
import { createBaseRequestOptions } from "./request-helpers";
// Web: 基于基础选项构造 fetch 的 RequestInit
export function createWebRequestOptions(
config: RequestConfig,
fullURL: string
): RequestInit & { timeout?: number; fullURL?: string } {
const baseOptions = createBaseRequestOptions(config) as {
method: string;
headers: Record<string, string>;
data: any;
timeout?: number;
signal?: AbortSignal;
};
const { method, headers, data, timeout, signal } = baseOptions;
const options: RequestInit & { timeout?: number; fullURL?: string } = {
method,
headers,
signal,
timeout,
fullURL,
} as any;
if (method !== 'GET' && method !== 'HEAD') {
if (
(typeof FormData !== 'undefined' && data instanceof FormData) ||
(typeof URLSearchParams !== 'undefined' && data instanceof URLSearchParams) ||
(typeof Blob !== 'undefined' && data instanceof Blob) ||
(typeof ArrayBuffer !== 'undefined' && data instanceof ArrayBuffer)
) {
(options as any).body = data;
} else if (typeof data === 'object' && data !== null) {
const contentType = headers['Content-Type'] || headers['content-type'] || '';
if (contentType.includes('application/x-www-form-urlencoded')) {
const formData = new URLSearchParams();
Object.entries(data).forEach(([key, value]) => {
if (Array.isArray(value)) {
value.forEach((item, index) => {
formData.append(`${key}[${index}]`, String(item));
});
} else {
formData.append(key, String(value));
}
});
(options as any).body = formData;
} else {
(options as any).body = JSON.stringify(data);
if (!headers['Content-Type'] && !headers['content-type']) {
(options.headers as Record<string, string>)['Content-Type'] = 'application/json';
}
}
} else if (data !== undefined) {
(options as any).body = String(data);
}
}
return options;
}
// Web 环境:将 fetch Response 转为标准 ResponseData,并根据 responseType 解析 body
export async function transformFetchResponse(
response: Response,
config: RequestConfig
): Promise<ResponseData<any>> {
const headers = parseHeaders((response as any).headers);
let data: any;
try {
const responseType = config.responseType || 'json';
switch (responseType) {
case 'json':
data = await (response as any).json();
break;
case 'text':
data = await (response as any).text();
break;
case 'blob':
data = await (response as any).blob();
break;
case 'arraybuffer':
data = await (response as any).arrayBuffer();
break;
default:
data = await (response as any).json();
}
} catch (_e) {
try {
data = await (response as any).text();
} catch {
data = null;
}
}
return {
data,
status: (response as any).status,
statusText: (response as any).statusText,
headers,
config,
};
}