-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathrequest.ts
More file actions
119 lines (106 loc) · 3 KB
/
request.ts
File metadata and controls
119 lines (106 loc) · 3 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
import { message } from 'antd';
import { testUrls } from '@/utils/helper';
import { logout } from './auth';
// eslint-disable-next-line @typescript-eslint/naming-convention
let _token = localStorage.getItem('token');
export const setToken = (token: string) => {
_token = token;
localStorage.setItem('token', token);
};
export const getToken = () => _token;
const SERVER = {
main:
process.env.NODE_ENV === 'production'
? [
'https://update.react-native.cn/api',
'https://update.reactnative.cn/api',
// "https://5.rnupdate.online/api",
]
: [process.env.PUBLIC_API ?? 'http://localhost:9000'],
};
// const baseUrl = `http://localhost:9000`;
// let baseUrl = SERVER.main[0];
// const baseUrl = `https://p.reactnative.cn/api`;
const getBaseUrl = (async () => {
return testUrls(SERVER.main.map((url) => `${url}/status`)).then((ret) => {
let baseUrl = SERVER.main[0];
if (ret) {
// remove /status
baseUrl = ret.replace('/status', '');
}
console.log('baseUrl', baseUrl);
return baseUrl;
});
})();
interface PushyResponse {
message?: string;
}
export class RequestError extends Error {
status?: number;
constructor(message: string, status?: number) {
super(message);
this.name = 'RequestError';
this.status = status;
}
}
export interface RequestOptions {
suppressErrorToast?: boolean;
}
export default async function request<T extends Record<any, any>>(
method: 'get' | 'post' | 'put' | 'delete',
path: string,
params?: Record<any, any>,
requestOptions: RequestOptions = {},
) {
const headers: HeadersInit = {};
const options: RequestInit = { method, headers };
const baseUrl = await getBaseUrl;
let url = `${baseUrl}${path}`;
if (_token) {
headers['x-accesstoken'] = _token;
}
if (params) {
if (method === 'get') {
url += `?${new URLSearchParams(params).toString()}`;
} else {
headers['content-type'] = 'application/json';
options.body = JSON.stringify(params);
}
}
try {
const response = await fetch(url, options);
if (response.status === 401) {
logout();
return;
}
const json = (await response.json()) as PushyResponse;
if (json.message === 'token expired' || json.message === 'token 过期') {
logout();
return;
}
if (response.status === 200) {
return json as T & PushyResponse;
}
const error = new RequestError(
json.message || `Request failed with status ${response.status}`,
response.status,
);
if (!requestOptions.suppressErrorToast && error.message) {
message.error(error.message);
}
throw error;
} catch (err) {
if (err instanceof RequestError) {
throw err;
}
if ((err as Error).message.includes('Unauthorized')) {
logout();
} else {
if (!requestOptions.suppressErrorToast) {
message.error(`错误:${(err as Error).message}`);
message.error('如有使用代理,请关闭代理后重试');
}
throw err;
}
}
}