-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.ts
71 lines (54 loc) · 2.33 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
interface Config {
api: string;
getAuthorization: () => string;
}
const config: Config = {
api: '',
getAuthorization: () => '',
};
function HeaderBuilder(header: object | null, body: object | string | null = null) : HeadersInit {
const headers = {
...header,
...(body ? { 'Content-Type': 'application/json' } : null),
...(config.getAuthorization() ? { authorization: config.getAuthorization() } : null),
};
return headers;
}
async function Handler(res: Response) {
const json = await res.json();
if (!res.ok) {
throw json;
} else {
return json;
}
}
export async function Get(endpoint: string, header: object | null = null, optionalApiAddress: string | null = null) {
const address = `${optionalApiAddress || config.api}${endpoint}`;
return fetch(address, { method: 'GET', headers: HeaderBuilder(header) })
.then(Handler);
}
export async function Post(endpoint: string, body: object | string | null, header: object | null = null, optionalApiAddress: object | null = null) {
const address = `${optionalApiAddress || config.api}${endpoint}`;
return fetch(address, { method: 'POST', body: JSON.stringify(body), headers: HeaderBuilder(header, body) })
.then(Handler);
}
export async function Patch(endpoint: string, body: object | string | null, header = null, optionalApiAddress = null) {
const address = `${optionalApiAddress || config.api}${endpoint}`;
return fetch(address, { method: 'PATCH', body: JSON.stringify(body), headers: HeaderBuilder(header, body) })
.then(Handler);
}
export async function Put(endpoint: string, body: object | string | null, header = null, optionalApiAddress = null) {
const address = `${optionalApiAddress || config.api}${endpoint}`;
return fetch(address, { method: 'PUT', body: JSON.stringify(body), headers: HeaderBuilder(header, body) })
.then(Handler);
}
export async function Delete(endpoint: string, body: object | string | null, header = null, optionalApiAddress = null) {
const address = `${optionalApiAddress || config.api}${endpoint}`;
return fetch(address, { method: 'DELETE', body: JSON.stringify(body), headers: HeaderBuilder(header, body) })
.then(Handler);
}
function Configurate(api: string = '', getAuthorization: () => string = () => '') {
config.api = api;
config.getAuthorization = getAuthorization;
}
export default { Configurate };