/
HttpAgentImpl.ts
556 lines (492 loc) · 15.9 KB
/
HttpAgentImpl.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
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
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
import * as Helpers from '@ima/helpers';
import {
HttpAgent,
HttpAgentRequestOptions,
HttpAgentResponse,
} from './HttpAgent';
import { HttpProxy, HttpProxyErrorParams } from './HttpProxy';
import { Cache } from '../cache/Cache';
import { GenericError } from '../error/GenericError';
import { CookieStorage } from '../storage/CookieStorage';
import { UnknownParameters } from '../types';
export interface HttpAgentImplCacheOptions {
prefix: string;
}
export interface HttpAgentImplConfig {
cacheOptions: HttpAgentImplCacheOptions;
defaultRequestOptions: HttpAgentRequestOptions;
}
/**
* Implementation of the {@link HttpAgent} interface with internal caching
* of completed and ongoing HTTP requests and cookie storage.
*/
export class HttpAgentImpl extends HttpAgent {
protected _proxy: HttpProxy;
protected _cache: Cache<HttpAgentResponse<unknown>>;
protected _cookie: CookieStorage;
protected _cacheOptions: HttpAgentImplCacheOptions;
protected _defaultRequestOptions: HttpAgentRequestOptions;
protected _Helper: typeof Helpers;
protected _internalCacheOfPromises = new Map();
/**
* Initializes the HTTP handler.
*
* @param proxy The low-level HTTP proxy for sending the HTTP
* requests.
* @param cache Cache to use for caching ongoing and completed
* requests.
* @param cookie The cookie storage to use internally.
* @param Helper The IMA.js helper methods.
* @param config Configuration of the HTTP handler for
* the current application environment, specifying the various
* default request option values and cache option values.
* @example
* http
* .get('url', { data: data }, {
* ttl: 2000,
* repeatRequest: 1,
* withCredentials: true,
* timeout: 2000,
* accept: 'application/json',
* language: 'en'
* })
* .then((response) => {
* //resolve
* }
* .catch((error) => {
* //catch
* });
* @example
* http
* .setDefaultHeader('Accept-Language', 'en')
* .clearDefaultHeaders();
*/
constructor(
proxy: HttpProxy,
cache: Cache<HttpAgentResponse<unknown>>,
cookie: CookieStorage,
config: HttpAgentImplConfig,
Helper: typeof Helpers
) {
super();
/**
* HTTP proxy, used to execute the HTTP requests.
*/
this._proxy = proxy;
/**
* Internal request cache, used to cache completed request results.
*/
this._cache = cache;
/**
* Cookie storage, used to keep track of cookies received from the
* server and send them with the subsequent requests to the server.
*/
this._cookie = cookie;
this._cacheOptions = config.cacheOptions;
this._defaultRequestOptions = config.defaultRequestOptions;
/**
* Tha IMA.js helper methods.
*/
this._Helper = Helper;
}
/**
* @inheritDoc
*/
get<B = unknown>(
url: string,
data?: UnknownParameters,
options?: Partial<HttpAgentRequestOptions>
): Promise<HttpAgentResponse<B>> {
return this._requestWithCheckCache<B>('get', url, data, options);
}
/**
* @inheritDoc
*/
post<B = unknown>(
url: string,
data?: UnknownParameters,
options?: Partial<HttpAgentRequestOptions>
): Promise<HttpAgentResponse<B>> {
return this._requestWithCheckCache<B>(
'post',
url,
data,
Object.assign({ cache: false }, options)
);
}
/**
* @inheritDoc
*/
put<B = unknown>(
url: string,
data?: UnknownParameters,
options?: Partial<HttpAgentRequestOptions>
): Promise<HttpAgentResponse<B>> {
return this._requestWithCheckCache<B>(
'put',
url,
data,
Object.assign({ cache: false }, options)
);
}
/**
* @inheritDoc
*/
patch<B = unknown>(
url: string,
data?: UnknownParameters,
options?: Partial<HttpAgentRequestOptions>
): Promise<HttpAgentResponse<B>> {
return this._requestWithCheckCache<B>(
'patch',
url,
data,
Object.assign({ cache: false }, options)
);
}
/**
* @inheritDoc
*/
delete<B = unknown>(
url: string,
data?: UnknownParameters,
options?: Partial<HttpAgentRequestOptions>
): Promise<HttpAgentResponse<B>> {
return this._requestWithCheckCache<B>(
'delete',
url,
data,
Object.assign({ cache: false }, options)
);
}
/**
* @inheritDoc
*/
getCacheKey(method: string, url: string, data?: UnknownParameters): string {
return (
this._cacheOptions.prefix + this._getCacheKeySuffix(method, url, data)
);
}
/**
* @inheritDoc
*/
invalidateCache(method: string, url: string, data?: UnknownParameters) {
const cacheKey = this.getCacheKey(method, url, data);
this._cache.delete(cacheKey);
}
/**
* @inheritDoc
*/
setDefaultHeader(header: string, value: string): this {
this._proxy.setDefaultHeader(header, value);
return this;
}
/**
* @inheritDoc
*/
clearDefaultHeaders(): this {
this._proxy.clearDefaultHeaders();
return this;
}
/**
* Attempts to clone the provided value, if possible. Values that cannot be
* cloned (e.g. promises) will be simply returned.
*
* @param value The value to clone.
* @return The created clone, or the provided value if the value cannot be
* cloned.
*/
_clone<V>(value: V): V {
if (
value !== null &&
typeof value === 'object' &&
!(value instanceof Promise)
) {
return this._Helper.clone(value);
}
return value;
}
/**
* Check cache and if data isn’t available then make real request.
*
* @param method The HTTP method to use.
* @param url The URL to which the request should be sent.
* @param data The data to send with the request.
* @param options Optional request options.
* @return A promise that resolves to the response
* with body parsed as JSON.
*/
_requestWithCheckCache<B>(
method: string,
url: string,
data?: UnknownParameters,
options?: Partial<HttpAgentRequestOptions>
): Promise<HttpAgentResponse<B>> {
const optionsWithDefault = this._prepareOptions(options);
if (optionsWithDefault.cache) {
const cachedData = this._getCachedData<B>(method, url, data);
if (cachedData) {
return cachedData;
}
}
return this._request<B>(method, url, data, optionsWithDefault);
}
/**
* Tests whether an ongoing or completed HTTP request for the specified URL
* and data is present in the internal cache and, if it is, the method
* returns a promise that resolves to the response body parsed as JSON.
*
* The method returns `null` if no such request is present in the
* cache.
*
* @param method The HTTP method used by the request.
* @param url The URL to which the request was made.
* @param data The data sent
* to the server with the request.
* @return {?Promise<HttpAgent~Response>} A promise that will resolve to the
* server response with the body parsed as JSON, or `null` if
* no such request is present in the cache.
*/
_getCachedData<B>(
method: string,
url: string,
data?: UnknownParameters
): Promise<HttpAgentResponse<B>> | null {
const cacheKey = this.getCacheKey(method, url, data);
if (this._internalCacheOfPromises.has(cacheKey)) {
return this._internalCacheOfPromises
.get(cacheKey)
.then((data: UnknownParameters) => this._clone(data));
}
if (this._cache.has(cacheKey)) {
const cacheData = this._cache.get(cacheKey) as HttpAgentResponse<B>;
return Promise.resolve<HttpAgentResponse<B>>(cacheData);
}
return null;
}
/**
* Sends a new HTTP request using the specified method to the specified
* url. The request will carry the provided data as query parameters if the
* HTTP method is GET, but the data will be sent as request body for any
* other request method.
*
* @param method HTTP method to use.
* @param url The URL to which the request is sent.
* @param data The data sent
* with the request.
* @param options Optional request options.
* @return {Promise<HttpAgent~Response>} A promise that resolves to the response
* with the body parsed as JSON.
*/
_request<B>(
method: string,
url: string,
data: UnknownParameters | undefined,
options: HttpAgentRequestOptions
): Promise<HttpAgentResponse<B>> {
const cacheKey = this.getCacheKey(method, url, data);
const cachePromise = this._proxy
.request<B>(method, url, data, options)
.then(
response => this._proxyResolved<B>(response),
error => this._proxyRejected<B>(error)
);
this._internalCacheOfPromises.set(cacheKey, cachePromise);
return cachePromise;
}
/**
* Handles successful completion of an HTTP request by the HTTP proxy.
*
* The method also updates the internal cookie storage with the cookies
* received from the server.
*
* @param {HttpAgent~Response} response Server response.
* @return {HttpAgent~Response} The post-processed server response.
*/
_proxyResolved<B>(response: HttpAgentResponse<B>): HttpAgentResponse<B> {
let agentResponse: HttpAgentResponse<B> = {
status: response.status,
body: response.body,
params: response.params,
headers: response.headers,
headersRaw: response.headersRaw,
cached: false,
};
const cacheKey = this.getCacheKey(
agentResponse.params.method,
agentResponse.params.url,
agentResponse.params.data
);
this._internalCacheOfPromises.delete(cacheKey);
if (this._proxy.haveToSetCookiesManually()) {
this._setCookiesFromResponse(agentResponse);
}
const { postProcessors, cache } = agentResponse.params.options;
if (Array.isArray(postProcessors)) {
for (const postProcessor of postProcessors) {
agentResponse = postProcessor<B>(agentResponse);
}
}
const pureResponse = this._cleanResponse(agentResponse);
if (cache) {
this._saveAgentResponseToCache(pureResponse);
}
return pureResponse;
}
/**
* Handles rejection of the HTTP request by the HTTP proxy. The method
* tests whether there are any remaining tries for the request, and if
* there are any, it attempts re-send the request.
*
* The method rejects the internal request promise if there are no tries
* left.
*
* @param error The error provided by the HttpProxy,
* carrying the error parameters, such as the request url, data,
* method, options and other useful data.
* @return {Promise<HttpAgent~Response>} A promise that will either resolve to a
* server's response (with the body parsed as JSON) if there are
* any tries left and the re-tried request succeeds, or rejects
* with an error containing details of the cause of the request's
* failure.
*/
_proxyRejected<B>(
error: GenericError<HttpProxyErrorParams>
): Promise<HttpAgentResponse<B>> {
const errorParams = error.getParams();
const method = errorParams.method;
const url = errorParams.url;
const data = errorParams.data;
const options = errorParams.options;
const isAborted =
options.fetchOptions?.signal?.aborted ||
options.abortController?.signal.aborted;
if (!isAborted && options.repeatRequest > 0) {
options.repeatRequest--;
return this._request(method, url, data, options);
} else {
const cacheKey = this.getCacheKey(method, url, data);
this._internalCacheOfPromises.delete(cacheKey);
const errorName = errorParams.errorName;
const errorMessage = `${errorName}: ima.core.http.Agent:_proxyRejected: ${error.message}`;
const agentError = new GenericError(errorMessage, errorParams);
return Promise.reject(agentError);
}
}
/**
* Prepares the provided request options object by filling in missing
* options with default values and adding extra options used internally.
*
* @param options Optional request options.
* @return Request options with set filled-in
* default values for missing fields, and extra options used
* internally.
*/
_prepareOptions(
options: Partial<HttpAgentRequestOptions> = {}
): HttpAgentRequestOptions {
const composedOptions = {
...this._defaultRequestOptions,
...options,
postProcessors: [
...(this._defaultRequestOptions?.postProcessors || []),
...(options?.postProcessors || []),
],
fetchOptions: {
...this._defaultRequestOptions?.fetchOptions,
...options?.fetchOptions,
headers: {
...this._defaultRequestOptions?.fetchOptions?.headers,
...options?.fetchOptions?.headers,
},
},
};
if (composedOptions.fetchOptions?.credentials === 'include') {
// mock default browser behavior for server-side (sending cookie with a fetch request)
composedOptions.fetchOptions.headers.Cookie =
this._cookie.getCookiesStringForCookieHeader();
}
return composedOptions;
}
/**
* Generates cache key suffix for an HTTP request to the specified URL with
* the specified data.
*
* @param method The HTTP method used by the request.
* @param url The URL to which the request is sent.
* @param data The data sent
* with the request.
* @return The suffix of a cache key to use for a request to the
* specified URL, carrying the specified data.
*/
_getCacheKeySuffix(
method: string,
url: string,
data?: UnknownParameters
): string {
let dataQuery = '';
if (data) {
try {
dataQuery = JSON.stringify(data).replace(/<\/script/gi, '<\\/script');
} catch (error) {
console.warn('The provided data does not have valid JSON format', data);
}
}
return `${method}:${url}?${dataQuery}`;
}
/**
* Sets all cookies from the `Set-Cookie` response header to the
* cookie storage.
*
* @param agentResponse The response of the server.
*/
_setCookiesFromResponse<B>(agentResponse: HttpAgentResponse<B>): void {
if (agentResponse.headersRaw) {
const receivedCookies = agentResponse.headersRaw.get('set-cookie');
if (receivedCookies) {
this._cookie.parseFromSetCookieHeader(receivedCookies);
}
}
}
/**
* Saves the server response to the cache to be used as the result of the
* next request of the same properties.
*
* @param agentResponse The response of the server.
*/
_saveAgentResponseToCache<B>(agentResponse: HttpAgentResponse<B>): void {
const cacheKey = this.getCacheKey(
agentResponse.params.method,
agentResponse.params.url,
agentResponse.params.data
);
agentResponse.cached = true;
this._cache.set(cacheKey, agentResponse, agentResponse.params.options.ttl);
agentResponse.cached = false;
}
/**
* Cleans cache response from data (abort controller, postProcessors), that cannot be persisted,
* before saving the data to the cache.
*/
_cleanResponse<B>(response: HttpAgentResponse<B>): HttpAgentResponse<B> {
/**
* Create copy of agentResponse without AbortController and AbortController signal and postProcessors.
* Setting agentResponse with AbortController or signal or postProcessors into cache would result in crash.
*/
const { signal, ...fetchOptions } =
response.params.options.fetchOptions || {};
const { abortController, postProcessors, ...options } =
response.params.options || {};
options.fetchOptions = fetchOptions;
const pureResponse = {
...response,
params: { ...response.params, options: { ...options } },
};
if (pureResponse.params.options.keepSensitiveHeaders !== true) {
pureResponse.headers = {};
pureResponse.params.options.fetchOptions.headers = {};
delete pureResponse.headersRaw;
}
return pureResponse;
}
}