-
Notifications
You must be signed in to change notification settings - Fork 0
/
httpsService.ts
112 lines (93 loc) · 3.06 KB
/
httpsService.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
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
const apiToken = '::tokenMocked::';
const manageResponse = async <T>(response: Response): Promise<T> => {
if (!response.ok) {
throw response;
}
return response.json();
};
interface IHeaders {
[key: string]: string;
}
class HttpService {
headers: IHeaders = { 'Content-Type': 'application/json' };
setGlobalHeaders(headers: IHeaders) {
this.headers = { ...this.headers, ...headers };
}
setTokenAuthorizationHeader = () => {
const getAllCookies = (): Record<string, string> => document.cookie
.split(';')
.reduce((ac, str) => Object.assign(ac, { [str.split('=')[0].trim()]: str.split('=')[1] }), {});
const { __px_uidtk: token } = getAllCookies();
this.setGlobalHeaders({
'x-api-key': apiToken as string,
});
if (token) {
this.setGlobalHeaders({
Authorization: `Bearer ${token}`,
});
}
};
async get<T>(endpoint: string, params?: Record<string, string>, headers = {}): Promise<T> {
this.setTokenAuthorizationHeader();
const urlParams = params
? (`?${new URLSearchParams(params)}`)
: '';
const url = `${endpoint}${urlParams}`;
const response = await fetch(url, {
headers: {
...this.headers,
...headers,
},
});
return manageResponse(response);
}
async post<T>(endpoint: string, data = {}, headers = {}): Promise<T> {
this.setTokenAuthorizationHeader();
const response = await fetch(`${endpoint}`, {
method: 'POST',
headers: {
...this.headers,
...headers,
},
body: JSON.stringify(data),
});
return manageResponse<T>(response);
}
async put<T>(endpoint: string, data = {}, headers = {}): Promise<T | any> {
this.setTokenAuthorizationHeader();
const response = await fetch(`${endpoint}`, {
method: 'PUT',
headers: {
...this.headers,
...headers,
},
body: JSON.stringify(data),
});
return manageResponse(response);
}
async patch<T>(endpoint: string, data = {}, headers = {}): Promise<T | any> {
this.setTokenAuthorizationHeader();
const response = await fetch(`${endpoint}`, {
method: 'PATCH',
headers: {
...this.headers,
...headers,
},
body: JSON.stringify(data),
});
return manageResponse(response);
}
async delete<T>(endpoint: string, data = {}, headers = {}): Promise<T | any> {
this.setTokenAuthorizationHeader();
const response = await fetch(`${endpoint}`, {
method: 'DELETE',
headers: {
...this.headers,
...headers,
},
body: JSON.stringify(data),
});
return manageResponse(response);
}
}
export const httpService = new HttpService();