-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathbasicHttpClient.ts
361 lines (323 loc) · 10.2 KB
/
basicHttpClient.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
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
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
// Copyright 2020 Cognite AS
import fetch, { Response } from 'cross-fetch';
import { DEFAULT_DOMAIN } from '../constants';
import { isJson } from '../utils';
import { HttpError, type HttpErrorData } from './httpError';
import type { HttpHeaders } from './httpHeaders';
/**
* The `BasicHttpClient` class provides a simplified HTTP client for making
* requests to a server. It abstracts away the underlying HTTP client and
* the complexities of handling different response types and error handling,
* making it easier to interact with HTTP APIs.
*
* This class includes static methods for:
* - Validating HTTP status codes.
* - Throwing custom error responses.
* - Handling JSON, text, and array buffer responses.
* - Selecting the appropriate response handler based on the expected response type.
*
* The `BasicHttpClient` is designed to be used in scenarios where you need to
* make HTTP requests and handle responses in a consistent and predictable manner.
* It ensures that responses are correctly parsed and that errors are properly
* propagated, allowing for robust error handling.
*
* @remarks
* This class relies on the `cross-fetch` library for making HTTP requests,
* and it uses custom error and header types defined in the project.
*
* @see {@link HttpError}
* @see {@link HttpHeaders}
* @see {@link HttpResponseType}
*/
export class BasicHttpClient {
private static validateStatusCode(status: number) {
return status >= 200 && status < 300;
}
private static throwCustomErrorResponse<T>(response: HttpResponse<T>) {
throw new HttpError(
response.status,
response.data as HttpErrorData,
response.headers
);
}
private static jsonResponseHandler<ResponseType>(
res: Response
): Promise<ResponseType> {
return res.json() as Promise<ResponseType>;
}
private static textResponseHandler<ResponseType>(
res: Response
): Promise<ResponseType> {
return res.text() as unknown as Promise<ResponseType>;
}
private static arrayBufferResponseHandler<ResponseType>(
res: Response
): Promise<ResponseType> {
return res
.blob()
.then((blob) =>
new Response(blob).arrayBuffer()
) as unknown as Promise<ResponseType>;
}
private static getResponseHandler<ResponseType>(
responseType?: HttpResponseType
): ResponseHandler<ResponseType> {
switch (responseType) {
case HttpResponseType.ArrayBuffer:
return BasicHttpClient.arrayBufferResponseHandler;
case HttpResponseType.Text:
return BasicHttpClient.textResponseHandler;
default:
return BasicHttpClient.jsonResponseHandler;
}
}
private static convertFetchHeaders(fetchHeaders: Headers) {
const headers: HttpHeaders = {};
fetchHeaders.forEach((value, key) => {
headers[key] = value;
});
return headers;
}
private static transformRequestBody(data: unknown) {
const isJSONStringifyable = isJson(data);
if (isJSONStringifyable) {
return JSON.stringify(data, null, 2);
}
return data;
}
private static resolveUrl(baseUrl: string, path: string) {
const trimmedBaseUrl = baseUrl.replace(/\/$/, '');
const pathWithPrefix = (path[0] === '/' ? '' : '/') + path;
return trimmedBaseUrl + pathWithPrefix.replace(/\/+$/, '');
}
private defaultHeaders: HttpHeaders = {};
/**
* A basic http client with the option of adding default headers,
* and the option of using a baseUrl.
* Note: If the path given starts with `https://`, the baseUrl is ignored.
*
* It handles query parameters, and request body data which gets encoded as json if
* needed.
*
* See HttpRequest.
*
* @param baseUrl
*/
constructor(protected baseUrl: string) {}
public setDefaultHeader(name: string, value: string) {
this.defaultHeaders[name] = value;
return this;
}
public getDefaultHeaders(): HttpHeaders {
return { ...this.defaultHeaders };
}
public setBaseUrl(baseUrl: string) {
this.baseUrl = baseUrl;
}
public getBaseUrl() {
return this.baseUrl;
}
public setCluster = (cluster: string) => {
this.baseUrl = `https://${cluster}.${DEFAULT_DOMAIN}`;
};
public get<ResponseType>(path: string, options: HttpRequestOptions = {}) {
return this.request<ResponseType>({
...options,
path,
method: HttpMethod.Get,
});
}
// TODO: responseType -> factory pattern
public post<ResponseType>(path: string, options: HttpRequestOptions = {}) {
return this.request<ResponseType>({
...options,
path,
method: HttpMethod.Post,
});
}
public put<ResponseType>(path: string, options: HttpRequestOptions = {}) {
return this.request<ResponseType>({
...options,
path,
method: HttpMethod.Put,
});
}
public delete<ResponseType>(path: string, options: HttpRequestOptions = {}) {
return this.request<ResponseType>({
...options,
path,
method: HttpMethod.Delete,
});
}
public patch<ResponseType>(path: string, options: HttpRequestOptions = {}) {
return this.request<ResponseType>({
...options,
path,
method: HttpMethod.Patch,
});
}
protected async preRequest(request: HttpRequest): Promise<HttpRequest> {
const populatedHeaders = this.populateDefaultHeaders(request.headers);
return {
...request,
headers: populatedHeaders,
};
}
protected async postRequest<T>(
response: HttpResponse<T>,
_: HttpRequest,
__: HttpRequest
): Promise<HttpResponse<T>> {
const requestIsOk = BasicHttpClient.validateStatusCode(response.status);
if (!requestIsOk) {
BasicHttpClient.throwCustomErrorResponse(response);
}
return response;
}
protected populateDefaultHeaders(headers: HttpHeaders = {}) {
return {
...this.defaultHeaders,
...headers,
};
}
protected async rawRequest<ResponseType>(
request: HttpRequest
): Promise<HttpResponse<ResponseType>> {
const url = this.constructUrl(request.path, request.params);
const headers = headersWithDefaultField(
request.headers || {},
'Accept',
'application/json'
);
let body = request.data;
if (isJson(body)) {
body = BasicHttpClient.transformRequestBody(body);
headers['Content-Type'] = 'application/json';
}
const res = await fetch(url, {
// @ts-ignore
body,
method: request.method,
headers,
});
const responseHandler = BasicHttpClient.getResponseHandler<ResponseType>(
request.responseType
);
// Cloning to fallback on text response if response is failing the responsehandler.
// node-fetch < 3.0 will hang on clone() for large responses, that is why the parallel promises https://github.com/node-fetch/node-fetch#custom-highwatermark
const resClone = res.clone();
const [data, textFallback] = await Promise.all([
responseHandler(res).catch(() => undefined),
resClone.text() as unknown as Promise<ResponseType>,
]);
return {
headers: BasicHttpClient.convertFetchHeaders(res.headers),
status: res.status,
data: data || textFallback,
};
}
protected async request<ResponseType>(request: HttpRequest) {
const mutatedRequest = await this.preRequest(request);
const rawResponse = await this.rawRequest<ResponseType>(mutatedRequest);
return this.postRequest(rawResponse, request, mutatedRequest);
}
private constructUrl<T extends object>(path: string, params?: T) {
let url = path;
const hasQueryParams = !!params && Object.keys(params).length > 0;
if (hasQueryParams) {
const normalizedParams: Record<string, string> = Object.entries(
params
).reduce(
(acc, [key, value]) => {
switch (typeof value) {
case 'undefined': {
return acc;
}
case 'string':
case 'number':
case 'boolean': {
acc[key] = `${value}`;
return acc;
}
case 'object': {
if (Array.isArray(value)) {
acc[key] = `[${value.join(',')}]`;
}
return acc;
}
default: {
throw new Error(
`Unsupported value query parameter type: ${typeof value}, ${key}: ${value}`
);
}
}
},
{} as Record<string, string>
);
const search = new URLSearchParams(normalizedParams).toString();
url += `?${search}`;
}
const urlContainsHost = url.match(/^https?:\/\//i) !== null;
if (urlContainsHost) {
return url;
}
return BasicHttpClient.resolveUrl(this.baseUrl, url);
}
}
function lowercaseHeadersKeys(headers: HttpHeaders): string[] {
const keys: string[] = [];
for (const key in headers) {
keys.push(key.toLowerCase());
}
return keys;
}
export function headersWithDefaultField(
headers: HttpHeaders,
fieldName: string,
fieldValue: string
): HttpHeaders {
const lowercaseHeaders = lowercaseHeadersKeys(headers);
const lowercaseKey = fieldName.toLowerCase();
if (!lowercaseHeaders.includes(lowercaseKey)) {
headers[fieldName] = fieldValue;
}
return headers;
}
export interface HttpRequest extends HttpRequestOptions {
path: string;
method: HttpMethod;
}
export interface HttpRequestOptions {
data?: unknown | null | undefined;
params?: HttpQueryParams;
headers?: HttpHeaders;
responseType?: HttpResponseType;
/**
* Set this to 'true' if you want to send credentials (access token) with the request to other domains than the specified base url.
*/
withCredentials?: boolean;
}
export interface HttpResponse<T> {
data: T;
status: number;
headers: HttpHeaders;
}
export enum HttpMethod {
Get = 'GET',
Post = 'POST',
Put = 'PUT',
Delete = 'DELETE',
Patch = 'PATCH',
}
type HttpResponseType = 'json' | 'arraybuffer' | 'text';
export const HttpResponseType = {
Json: 'json' as HttpResponseType,
ArrayBuffer: 'arraybuffer' as HttpResponseType,
Text: 'text' as HttpResponseType,
};
export type HttpQueryParams = object;
type ResponseHandler<ResponseType> = (res: Response) => Promise<ResponseType>;
export type HttpCall = <ResponseType>(
path: string,
options?: HttpRequestOptions
) => Promise<HttpResponse<ResponseType>>;