-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathhttp.ts
More file actions
103 lines (87 loc) · 2.71 KB
/
Copy pathhttp.ts
File metadata and controls
103 lines (87 loc) · 2.71 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
export type FetchConfig = Omit<RequestInit, 'headers'> & {
headers?: Record<string, string>;
};
export type HttpBody = BodyInit | object;
export class BaseHttpClientError extends Error {
response: Response;
constructor(response: Response) {
super(`HTTP request failed: ${response.statusText} (${response.url})`)
this.response = response
}
}
export abstract class BaseHttpClient {
_baseUrl: string;
_requestHeaders = {
'Accept': 'application/json',
'Authorization': '',
'Content-Type': 'application/json'
};
_abortSignal?: AbortSignal;
constructor(baseUrl: string, signal?: AbortSignal) {
this._baseUrl = baseUrl;
this._abortSignal = signal;
}
url(rest: string) {
return this._baseUrl + rest
}
_get(url: string, config?: FetchConfig): Promise<Response> {
return this._send(url, 'GET', undefined, config);
}
_post(url: string, body?: HttpBody, config?: FetchConfig): Promise<Response> {
return this._send(url, 'POST', body, config);
}
_put(url: string, body?: HttpBody, config?: FetchConfig): Promise<Response> {
return this._send(url, 'PUT', body, config);
}
_patch(url: string, body?: HttpBody, config?: FetchConfig): Promise<Response> {
return this._send(url, 'PATCH', body, config);
}
_delete(url: string, config?: FetchConfig): Promise<Response> {
return this._send(url, 'DELETE', undefined, config);
}
async _send(
url: string,
method: string,
body?: HttpBody,
config?: FetchConfig,
): Promise<Response> {
const { headers: configHeaders, ...restConfig } = config ?? {};
const mergedHeaders: Record<string, string> = {
...this._requestHeaders,
...configHeaders,
};
const requestOptions = {
method,
body: undefined as BodyInit | undefined,
headers: mergedHeaders,
signal: this._abortSignal,
...restConfig,
};
// Let the browser set Content-Type (and multipart boundary) for FormData:
if (body instanceof FormData) {
delete mergedHeaders['Content-Type'];
requestOptions.body = body;
}
else if (body !== null && body !== undefined && (
mergedHeaders['Content-Type'] === 'application/json'
|| (
typeof body === 'object'
&& !(body instanceof Blob)
&& !(body instanceof ArrayBuffer)
&& !ArrayBuffer.isView(body)
&& !(body instanceof URLSearchParams)
&& !(body instanceof ReadableStream)
)
)) {
requestOptions.body = JSON.stringify(body);
}
else {
requestOptions.body = body as BodyInit;
}
const response = await fetch(this.url(url), requestOptions);
if (!response.ok) {
throw new BaseHttpClientError(response);
}
return response;
}
}