forked from riccardoperra/codeimage
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclient.ts
More file actions
71 lines (60 loc) · 1.78 KB
/
client.ts
File metadata and controls
71 lines (60 loc) · 1.78 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
import {getAuth0State} from '@codeimage/store/auth/auth0';
export interface RequestParams {
body?: unknown;
querystring?: Record<string, string | number | boolean | symbol>;
params?: Record<string, any>;
headers?: Record<string, string | null | undefined>;
}
export interface Schema {
request: any;
response: any;
}
export async function makeFetch(
input: RequestInfo,
requestParams: Omit<RequestInit, keyof RequestParams> & RequestParams,
): Promise<Response> {
const {getToken} = getAuth0State();
let url = typeof input === 'string' ? input : input.url;
const headers = new Headers();
const request: RequestInit = {...(requestParams as RequestInit)};
try {
const token = await getToken();
if (token) {
headers.append('Authorization', `Bearer ${token}`);
}
} catch (e) {}
if (requestParams.querystring) {
const querystring = new URLSearchParams();
for (const [key, value] of Object.entries(requestParams.querystring)) {
querystring.set(key, String(value));
}
url += `?${querystring.toString()}`;
}
if (requestParams.body) {
request.body = JSON.stringify(requestParams.body);
if (typeof requestParams.body === 'object') {
headers.set('Content-Type', 'application/json');
}
}
if (requestParams.headers) {
for (const [key, value] of Object.entries(requestParams.headers)) {
if (value) {
headers.append(key, value);
}
}
}
if (requestParams.params) {
for (const [key, value] of Object.entries(requestParams.params)) {
url = url.replace(`:${key}`, value);
}
}
request.headers = headers;
return fetch(url, request).then(async res => {
if (!res.ok) {
return res.json().then(error => {
return Promise.reject(error);
});
}
return res;
});
}