-
Notifications
You must be signed in to change notification settings - Fork 530
Expand file tree
/
Copy pathHttpClient.ts
More file actions
161 lines (143 loc) · 3.77 KB
/
Copy pathHttpClient.ts
File metadata and controls
161 lines (143 loc) · 3.77 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
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
import {
AUTHENTICITY_TOKEN_HEADER,
getAuthenticityToken,
} from './AuthenticityTokenStore';
export type ResponseValidator<ResponseType> = (
bodyJson: Record<string, unknown> | unknown[]
) => ResponseType;
export type GetResponse<ResponseType> = {
value: ResponseType;
response: Response;
};
// Narrow the type of an error to NetworkError
export function isNetworkError(error: unknown): error is NetworkError {
return error instanceof NetworkError;
}
/**
* Error thrown by these functions when the response is not ok, which includes a
* reference to the response object.
*/
export class NetworkError extends Error {
constructor(message: string, public response: Response) {
super(message);
this.name = 'NetworkError';
// Needed for TypeScript to register this class correctly in ES5
// https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#extending-built-ins-like-error-array-and-map-may-no-longer-work
Object.setPrototypeOf(this, NetworkError.prototype);
}
getDetails() {
const headers: {[key: string]: string} = {};
this.response.headers.forEach((value, key) => {
headers[key] = value;
});
return {
status: this.response.status,
statusText: this.response.statusText,
url: this.response.url,
type: this.response.type,
headers,
};
}
}
/**
* Get a JSON response from the given endpoint and
* return it as the specified type. Can also perform
* response validation if provided a validator function.
*/
async function fetchJson<ResponseType>(
endpoint: string,
init?: RequestInit,
validator?: ResponseValidator<ResponseType>
): Promise<GetResponse<ResponseType>> {
const response = await fetch(endpoint, init);
if (!response.ok) {
throw new NetworkError(
response.status + ' ' + response.statusText,
response
);
}
const json = await response.json();
let value: ResponseType = json;
if (validator) {
value = validator(json);
}
return {
value,
response,
};
}
/**
* Sends a request to the given endpoint. Adds the Rails authenticity
* token if useAuthenticityToken is true.
*/
async function sendRequest(
method: string,
endpoint: string,
body?: BodyInit,
useAuthenticityToken = false,
headers: Record<string, string> = {}
): Promise<Response> {
if (useAuthenticityToken) {
const token = await getAuthenticityToken();
headers[AUTHENTICITY_TOKEN_HEADER] = token;
}
const response = await fetch(endpoint, {
method,
body,
headers,
});
if (!response.ok) {
throw new NetworkError(
response.status + ' ' + response.statusText,
response
);
}
return response;
}
/**
* Performs a GET request to the given endpoint. Use {@link fetchJson}
* to automatically unwrap the response JSON as a typed object.
*/
async function get(
endpoint: string,
useAuthenticityToken = false,
headers: Record<string, string> = {}
): Promise<Response> {
return sendRequest('GET', endpoint, undefined, useAuthenticityToken, headers);
}
async function put(
endpoint: string,
body?: BodyInit,
useAuthenticityToken = false,
headers: Record<string, string> = {}
): Promise<Response> {
return sendRequest('PUT', endpoint, body, useAuthenticityToken, headers);
}
async function post(
endpoint: string,
body?: BodyInit,
useAuthenticityToken = false,
headers: Record<string, string> = {}
): Promise<Response> {
return sendRequest('POST', endpoint, body, useAuthenticityToken, headers);
}
async function deleteRequest(
endpoint: string,
useAuthenticityToken = false,
headers: Record<string, string> = {}
): Promise<Response> {
return sendRequest(
'DELETE',
endpoint,
undefined,
useAuthenticityToken,
headers
);
}
export default {
delete: deleteRequest,
fetchJson,
post,
put,
get,
};