-
Notifications
You must be signed in to change notification settings - Fork 16
Expand file tree
/
Copy pathclient.ts
More file actions
481 lines (421 loc) · 12.3 KB
/
client.ts
File metadata and controls
481 lines (421 loc) · 12.3 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
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
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
import Axios, { AxiosInstance, AxiosRequestConfig, AxiosResponse } from 'axios';
import { IHttpClient } from './client-interface';
import { HttpResponse } from './http-response';
import configStore from '../config-handler';
import authHandler from '../auth-handler';
import { hasProxy, getProxyUrl, getProxyConfig, getProxyConfigForHost } from '../proxy-helper';
/**
* Derive request host from baseURL or url for NO_PROXY checks.
*/
function getRequestHost(baseURL?: string, url?: string): string | undefined {
const toTry = [baseURL, url].filter(Boolean) as string[];
for (const candidateUrl of toTry) {
try {
const parsed = new URL(candidateUrl.startsWith('http') ? candidateUrl : `https://${candidateUrl}`);
return parsed.hostname || undefined;
} catch {
// Invalid URL; try next candidate (baseURL or url)
}
}
return undefined;
}
export type HttpClientOptions = {
disableEarlyAccessHeaders?: boolean;
};
export class HttpClient implements IHttpClient {
/**
* The request configuration.
*/
private request: AxiosRequestConfig;
/**
* The request configuration.
*/
private readonly axiosInstance: AxiosInstance;
private disableEarlyAccessHeaders: boolean;
/**
* The payload format for a JSON or form-url-encoded request.
*/
private bodyFormat: BodyFormat = 'json';
/**
* Createa new pending HTTP request instance.
*/
constructor(request: AxiosRequestConfig = {}, options: HttpClientOptions = {}) {
this.request = request;
this.axiosInstance = Axios.create();
this.disableEarlyAccessHeaders = options.disableEarlyAccessHeaders || false;
// Sets payload format as json by default
this.asJson();
}
/**
* Create a reusable HttpClient instance.
*
* @returns {HttpClient}
*/
static create(request: AxiosRequestConfig = {}): HttpClient {
return new this(request);
}
/**
* Returns the Axios request config.
*
* @returns {AxiosRequestConfig}
*/
requestConfig(): AxiosRequestConfig {
return this.request;
}
/**
* Resets the request config.
*
* @returns {AxiosRequestConfig}
*/
resetConfig(): HttpClient {
this.request = {};
return this;
}
/**
* Use the given `baseUrl` for all requests.
*
* @param {String} baseUrl
*
* @returns {HttpClient}
*/
baseUrl(baseUrl: string): HttpClient {
if (typeof baseUrl !== 'string') {
throw new Error(`The base URL must be a string. Received "${typeof baseUrl}"`);
}
this.request.baseURL = baseUrl;
return this;
}
/**
* Add request headers.
* @returns {HttpClient}
*/
headers(headers: any): HttpClient {
this.request.headers = { ...this.request.headers, ...headers };
return this;
}
/**
* Add query parameters to the request.
*
* @param {Object} queryParams
*
* @returns {HttpClient}
*/
queryParams(queryParams: object): HttpClient {
this.request.params = { ...this.request.params, ...queryParams };
return this;
}
/**
* Add basic authentication via `username` and `password` to the request.
*
* @param {String} username
* @param {String} password
*
* @returns {HttpClient}
*/
basicAuth(username: string, password: string): HttpClient {
this.request.auth = { username, password };
return this;
}
/**
* Add an authorization `token` to the request.
*
* @param {String} token
* @param {String} type
*
* @returns {HttpClient}
*/
token(token: string, type: string = 'Bearer'): HttpClient {
return this.headers({
Authorization: `${type} ${token}`.trim(),
});
}
/**
* Merge your own custom Axios options into the request.
*
* @param {Object} options
*
* @returns {HttpClient}
*/
options(options: AxiosRequestConfig = {}): HttpClient {
Object.assign(this.request, options);
return this;
}
/**
* Add a request payload.
*
* @param {*} data
*
* @returns {HttpClient}
*/
payload(data: any): HttpClient {
this.request.data = data;
return this;
}
/**
* Define the request `timeout` in milliseconds.
*
* @param {Number} timeout
*
* @returns {HttpClient}
*/
timeout(timeout: number): HttpClient {
this.request.timeout = timeout;
return this;
}
/**
* Tell HttpClient to send the request as JSON payload.
*
* @returns {HttpClient}
*/
asJson(): HttpClient {
return this.payloadFormat('json').contentType('application/json');
}
/**
* Tell HttpClient to send the request as form parameters,
* encoded as URL query parameters.
*
* @returns {HttpClient}
*/
asFormParams(): HttpClient {
return this.payloadFormat('formParams').contentType('application/x-www-form-urlencoded');
}
/**
* Set the request payload format.
*
* @param {String} format
*
* @returns {HttpClient}
*/
payloadFormat(format: BodyFormat): HttpClient {
this.bodyFormat = format;
return this;
}
/**
* Set the `Accept` request header. This indicates what
* content type the server should return.
*
* @param {String} accept
*
* @returns {HttpClient}
*/
accept(accept: string): HttpClient {
return this.headers({ Accept: accept });
}
/**
* Set the `Accept` request header to JSON. This indicates
* that the server should return JSON data.
*
* @param {String} accept
*
* @returns {HttpClient}
*/
acceptJson(): HttpClient {
return this.accept('application/json');
}
/**
* Set the `Content-Type` request header.
*
* @param {String} contentType
*
* @returns {HttpClient}
*/
contentType(contentType: string): HttpClient {
return this.headers({ 'Content-Type': contentType });
}
/**
* Send an HTTP GET request, optionally with the given `queryParams`.
*
* @param {String} url
* @param {Object} queryParams
*
* @returns {HttpResponse}
*
* @throws
*/
async get<R>(url: string, queryParams: object = {}): Promise<HttpResponse<R>> {
this.queryParams(queryParams);
return this.send<R>('GET', url);
}
/**
* Send an HTTP POST request, optionally with the given `payload`.
*
* @param {String} url
* @param {Object} payload
*
* @returns {HttpResponse}
*
* @throws
*/
async post<R>(url: string, payload?: any): Promise<HttpResponse<R>> {
if (payload) {
this.payload(payload);
}
return this.send<R>('POST', url);
}
/**
* Send an HTTP PUT request, optionally with the given `payload`.
*
* @param {String} url
* @param {Object} payload
*
* @returns {HttpResponse}
*
* @throws
*/
async put<R>(url: string, payload?: any): Promise<HttpResponse<R>> {
if (payload) {
this.payload(payload);
}
return this.send<R>('PUT', url);
}
/**
* Send an HTTP PATCH request, optionally with the given `payload`.
*
* @param {String} url
* @param {Object} payload
*
* @returns {HttpResponse}
*
* @throws
*/
async patch<R>(url: string, payload?: any): Promise<HttpResponse<R>> {
if (payload) {
this.payload(payload);
}
return this.send<R>('PATCH', url);
}
/**
* Send an HTTP DELETE request, optionally with the given `queryParams`.
*
* @param {String} url
* @param {Object} queryParams
*
* @returns {HttpResponse}
*
* @throws
*/
async delete<R>(url: string, queryParams: object = {}): Promise<HttpResponse<R>> {
this.queryParams(queryParams);
return this.send<R>('DELETE', url);
}
/**
* Send the HTTP request.
*
* @param {String} method
* @param {String} url
*
* @returns {HttpResponse}
*
* @throws
*/
async send<R>(method: HttpMethod, url: string): Promise<HttpResponse<R>> {
try {
return new HttpResponse<R>(await this.createAndSendRequest(method, url));
} catch (error: any) {
if (error.response) {
return new HttpResponse(error.response);
}
throw error;
}
}
/**
* Create and send the HTTP request.
*
* @param {String} method
* @param {String} url
*
* @returns {Request}
*/
async createAndSendRequest(method: HttpMethod, url: string): Promise<AxiosResponse> {
let counter = 0;
this.axiosInstance.interceptors.response.use(null, async (error) => {
const { message, response, code } = error;
// Don't retry proxy connection errors - fail fast
const proxyErrorCodes = ['ECONNREFUSED', 'ETIMEDOUT', 'ENOTFOUND', 'ERR_BAD_RESPONSE'];
const isProxyConfigured = this.request.proxy || hasProxy();
if (isProxyConfigured && (proxyErrorCodes.includes(code) || message?.includes('ERR_BAD_RESPONSE'))) {
const proxyUrl = this.request.proxy && typeof this.request.proxy === 'object'
? `${this.request.proxy.protocol}://${this.request.proxy.host}:${this.request.proxy.port}`
: getProxyUrl();
return Promise.reject(new Error(`Proxy error: Unable to connect to proxy server at ${proxyUrl}. Please verify your proxy configuration.`));
}
if (response?.data?.error_message?.includes('access token is invalid or expired')) {
const token = await this.refreshToken();
this.headers({ ...this.request.headers, authorization: token.authorization });
return await this.axiosInstance({
url,
method,
withCredentials: true,
...this.request,
data: this.prepareRequestPayload(),
});
}
if (
!(message.includes('timeout') || message.includes('Network Error') || message.includes('getaddrinfo ENOTFOUND'))
) {
return Promise.reject(error);
}
if (counter < 1) {
counter++;
return await this.axiosInstance({
url,
method,
withCredentials: true,
...this.request,
data: this.prepareRequestPayload(),
});
}
return Promise.reject(error);
});
if (!this.disableEarlyAccessHeaders) {
// Add early access header by default
const earlyAccessHeaders = configStore.get(`earlyAccessHeaders`);
if (earlyAccessHeaders && Object.keys(earlyAccessHeaders).length > 0) {
this.headers({ 'x-header-ea': Object.values(earlyAccessHeaders).join(',') });
}
}
// Configure proxy if available. NO_PROXY has priority: hosts in NO_PROXY never use proxy.
if (!this.request.proxy) {
const host = getRequestHost(this.request.baseURL, url);
const proxyConfig = host ? getProxyConfigForHost(host) : getProxyConfig();
if (proxyConfig) {
this.request.proxy = proxyConfig;
}
}
return await this.axiosInstance({
url,
method,
withCredentials: true,
...this.request,
data: this.prepareRequestPayload(),
});
}
/**
* Get the axios instance for interceptor access
*/
get interceptors() {
return this.axiosInstance.interceptors;
}
/**
* Returns the request payload depending on the selected request payload format.
*/
prepareRequestPayload(): any {
return this.bodyFormat === 'formParams' ? new URLSearchParams(this.request.data).toString() : this.request.data;
}
async refreshToken() {
const authorisationType = configStore.get('authorisationType');
if (authorisationType === 'BASIC') {
return Promise.reject('Your session is timed out, please login to proceed');
} else if (authorisationType === 'OAUTH') {
return authHandler
.compareOAuthExpiry(true)
.then(() => Promise.resolve({ authorization: `Bearer ${configStore.get('oauthAccessToken')}` }))
.catch((error) => Promise.reject(error));
} else {
return Promise.reject('You do not have permissions to perform this action, please login to proceed');
}
}
}
export interface HttpRequestConfig extends AxiosRequestConfig {}
type BodyFormat = 'json' | 'formParams';
type HttpMethod = 'GET' | 'HEAD' | 'POST' | 'PUT' | 'DELETE' | 'PATCH' | 'OPTIONS';