-
-
Notifications
You must be signed in to change notification settings - Fork 1.4k
/
api.ts
73 lines (64 loc) 路 1.94 KB
/
api.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
import storage from './storage';
/**
* Handles response according to content type
* @param {object} response
* @returns {promise}
*/
export function handleResponseType(response: Response): Promise<[boolean, any]> {
if (response.headers) {
const contentType = response.headers.get('Content-Type');
if (contentType?.includes('application/pdf')) {
return Promise.all([response.ok, response.blob()]);
}
if (contentType?.includes('application/json')) {
return Promise.all([response.ok, response.json()]);
}
// it includes all text types
if (contentType?.includes('text/')) {
return Promise.all([response.ok, response.text()]);
}
// unfortunately on download files there is no header available
if (response.url && response.url.endsWith('.tgz') === true) {
return Promise.all([response.ok, response.blob()]);
}
}
return Promise.all([response.ok, response.text()]);
}
const AuthHeader = 'Authorization';
class API {
public request<T>(
url: string,
method = 'GET',
options: RequestInit = { headers: {} }
): Promise<T> {
const token = storage.getItem('token');
const headers = new Headers(options.headers);
if (token && headers.has(AuthHeader) === false) {
headers.set(AuthHeader, `Bearer ${token}`);
options.headers = headers;
}
headers.set('x-client', 'verdaccio-ui');
return new Promise((resolve, reject) => {
fetch(url, {
method,
credentials: 'same-origin',
signal: options.signal,
...options,
})
.then(handleResponseType)
.then((response) => {
if (response[0]) {
resolve(response[1]);
} else {
// eslint-disable-next-line no-console
console.error(response);
reject(new Error('something went wrong'));
}
})
.catch((error) => {
reject(error);
});
});
}
}
export default new API();