-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.ts
76 lines (66 loc) · 1.79 KB
/
index.ts
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
import {
API_PREFIX,
LOGIN_TIP,
NETWORK_ERROR_TIP,
SUCCESS_CODE,
} from "./constant";
interface info {
token: string;
vin?: string[];
mobile?: string;
}
export interface CustomWindow extends Window {
info?: info;
}
interface errorMessage {
message: string;
}
export interface getParams {
[key: string]: string;
}
export interface postParams {
[key: string]: BodyInit;
}
declare const window: CustomWindow;
const getPath = (api: string) =>
api.startsWith("/") ? `${API_PREFIX}${api}` : api;
export const $fetch = async (api: string, options: RequestInit = {}) => {
// 设置超时
const controller = new AbortController();
const timeoutId = setTimeout(() => controller.abort(), 10 * 1000);
try {
const response = await fetch(api, {
headers: {
["content-type"]: "application/json",
},
signal: controller.signal,
...options,
});
const { status } = response;
if (status === SUCCESS_CODE) {
return response.json();
}
// 只有200才算作成功,其它都当作异常
throw new Error(`${status}`);
} catch (error) {
const { message } = error as errorMessage;
console.log("error", message);
return {
// 如果为401则返回登录话术,其他异常返回网络错误
errorMessage: +message === 401 ? LOGIN_TIP : NETWORK_ERROR_TIP,
};
} finally {
clearTimeout(timeoutId);
}
};
export const $get = (api: string, params: getParams = {}) => {
const queryArr = Object.entries(params).map(([k, v]) => `${k}=${v}`);
const queryStr = queryArr.length ? `?${queryArr.join("&")}` : "";
return $fetch(`${getPath(api)}${queryStr}`);
};
export const $post = (api: string, params: postParams = {}) => {
return $fetch(getPath(api), {
method: "POST",
body: JSON.stringify(params),
});
};