This repository has been archived by the owner on Feb 10, 2024. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 2
/
HttpService.ts
415 lines (373 loc) · 13.5 KB
/
HttpService.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
// Copyright (c) 2021-2022. Heusala Group Oy <info@heusalagroup.fi>. All rights reserved.
import { JsonAny, ReadonlyJsonAny } from "./Json";
import { RequestClientImpl } from "./RequestClientImpl";
import { Observer, ObserverCallback, ObserverDestructor } from "./Observer";
import { LogService } from "./LogService";
import { LogLevel } from "./types/LogLevel";
import { ResponseEntity } from "./request/types/ResponseEntity";
import { isRequestError } from "./request/types/RequestError";
import { getNextRetryDelay, HttpRetryPolicy, shouldRetry } from "./request/types/HttpRetryPolicy";
import { Method } from "./types/Method";
export { Method };
const LOG = LogService.createLogger('HttpService');
export enum HttpServiceEvent {
REQUEST_STARTED = "HttpService:requestStarted",
REQUEST_STOPPED = "HttpService:requestStopped"
}
export type HttpServiceDestructor = ObserverDestructor;
export class HttpService {
private static _defaultRetryDelay : number = 1000;
private static _requestLimit : number = 100;
private static _baseApiUrl : string | undefined;
private static _requestCount : number = 0;
private static _observer: Observer<HttpServiceEvent> = new Observer<HttpServiceEvent>("HttpService");
public static Event = HttpServiceEvent;
public static setLogLevel (level: LogLevel) {
LOG.setLogLevel(level);
RequestClientImpl.setLogLevel(level);
}
public static setRequestLimit (value : number ) {
this._requestLimit = value;
}
/**
* How long we should wait after a recoverable error happens until trying
* the request again. This is the base delay.
*
* This is active only if the retry policy has been defined but it does not
* include a base delay.
*
* @param value The time to wait in milliseconds
*/
public static setDefaultRetryLimit (value : number ) {
this._defaultRetryDelay = value;
}
/**
* Defines an optional base API URL which will be used if URL does not have a full URL (e.g. starts with "/api").
*
* This is required for browser compatible NodeJS SSR use case.
*
* @param url
*/
public static setBaseUrl (url : string | undefined) {
this._baseApiUrl = url;
}
public static on (
name: HttpServiceEvent,
callback: ObserverCallback<HttpServiceEvent>
): HttpServiceDestructor {
return this._observer.listenEvent(name, callback);
}
public static destroy (): void {
this._observer.destroy();
// FIXME: Cancel requests
}
public static hasOpenRequests () : boolean {
return this._requestCount >= 1;
}
public static getRequestCount () : number {
return this._requestCount;
}
public static async waitUntilNoOpenRequests () : Promise<void> {
if (!this.hasOpenRequests()) {
LOG.debug(`No open requests to wait`);
return;
}
LOG.debug(`waitUntilNoOpenRequests: Let's wait until no requests`);
return await new Promise((resolve, reject) => {
try {
let destructor : any | undefined = this.on(HttpServiceEvent.REQUEST_STOPPED, () => {
try {
if (!this.hasOpenRequests()) {
LOG.debug(`waitUntilNoOpenRequests: No requests anymore. We're ready!`);
destructor();
destructor = undefined;
resolve();
} else {
LOG.debug(`waitUntilNoOpenRequests: We still have ${this.getRequestCount()} requests`);
}
} catch (err) {
LOG.debug(`waitUntilNoOpenRequests: Canceling waiting: error: `, err);
reject(err);
}
});
} catch (err) {
LOG.debug(`waitUntilNoOpenRequests: Canceling waiting: error: `, err);
reject(err);
}
});
}
private static _prepareUrl (url : string) : string {
if (this._baseApiUrl && url.startsWith('/api')) {
return `${this._baseApiUrl}${url.substring('/api'.length)}`;
}
return url;
}
private static async _request<T> (
context : string,
method : Method,
url : string,
callback : () => T,
retryPolicy ?: HttpRetryPolicy,
attempt ?: number,
retryDelay ?: number
) : Promise<T | undefined> {
attempt = attempt ?? 0;
retryDelay = retryDelay ?? retryPolicy?.baseDelay ?? this._defaultRetryDelay;
if (attempt === 0 && this._requestCount >= this._requestLimit) {
throw new TypeError(`${context}: Too many requests: ${this._requestCount}`);
}
try {
if (attempt === 0) {
this._requestCount += 1;
if ( this._observer.hasCallbacks(HttpServiceEvent.REQUEST_STARTED) ) {
this._observer.triggerEvent(HttpServiceEvent.REQUEST_STARTED, url, method);
}
LOG.debug(`Started ${method} request to "${url} "(${this._requestCount} requests)`);
} else {
LOG.debug(`Started attempt ${attempt} for ${method} request to "${url} "(${this._requestCount} requests)`);
}
return await callback();
} catch (e) {
const code : any = (e as any)?.code;
const status = isRequestError(e) ? e.status : 0;
if (retryPolicy) {
if (shouldRetry(retryPolicy, attempt, method, status, code)) {
LOG.warn(`Error in ${method} "${url}": ${e} ${code} ${status}`);
LOG.debug(`Waiting next attempt for ${method} request to "${url} "(${this._requestCount} requests)`);
await this._waitForRetry(retryDelay);
retryDelay = getNextRetryDelay(retryDelay, retryPolicy);
return await this._request(context, method, url, callback, retryPolicy, attempt + 1, retryDelay);
} else {
throw e;
}
} else {
throw e;
}
} finally {
if (attempt === 0) {
this._requestCount -= 1;
if (this._observer.hasCallbacks(HttpServiceEvent.REQUEST_STOPPED)) {
this._observer.triggerEvent(HttpServiceEvent.REQUEST_STOPPED, url, method);
}
LOG.debug(`Stopped ${method} request to "${url}" (${this._requestCount} requests)`);
}
}
}
private static async _waitForRetry (time: number) : Promise<void> {
LOG.debug(`Waiting for retry time: `, time);
return new Promise( (resolve, reject) => {
try {
setTimeout(
() => {
resolve();
},
time
);
} catch (err) {
reject(err);
}
});
}
public static async getJson (
url : string,
headers ?: {[key: string]: string},
retryPolicy ?: HttpRetryPolicy
) : Promise<ReadonlyJsonAny | undefined> {
url = this._prepareUrl(url);
return this._request(
'getJson',
Method.GET,
url,
async () => {
const response : JsonAny | undefined = await RequestClientImpl.getJson(url, headers);
return response as ReadonlyJsonAny | undefined;
},
retryPolicy
);
}
public static async postJson (
url : string,
data ?: ReadonlyJsonAny,
headers ?: {[key: string]: string},
retryPolicy ?: HttpRetryPolicy
) : Promise<ReadonlyJsonAny | undefined> {
url = this._prepareUrl(url);
return this._request(
'postJson',
Method.POST,
url,
async () => {
const response : JsonAny | undefined = await RequestClientImpl.postJson(url, data as JsonAny, headers);
return response as ReadonlyJsonAny | undefined;
},
retryPolicy
);
}
public static async deleteJson (
url : string,
headers ?: {[key: string]: string},
retryPolicy ?: HttpRetryPolicy
) : Promise<ReadonlyJsonAny | undefined> {
url = this._prepareUrl(url);
return this._request(
'deleteJson',
Method.DELETE,
url,
async () => {
const response : JsonAny | undefined = await RequestClientImpl.deleteJson(url, headers);
return response as ReadonlyJsonAny | undefined;
},
retryPolicy
);
}
public static async getText (
url : string,
headers ?: {[key: string]: string},
retryPolicy ?: HttpRetryPolicy
) : Promise<string | undefined> {
url = this._prepareUrl(url);
return this._request(
'getText',
Method.GET,
url,
async () => {
const response : string | undefined = await RequestClientImpl.getText(url, headers);
return response as string | undefined;
},
retryPolicy
);
}
public static async postText (
url : string,
data ?: string,
headers ?: {[key: string]: string},
retryPolicy ?: HttpRetryPolicy
) : Promise<string | undefined> {
url = this._prepareUrl(url);
return this._request(
'postText',
Method.POST,
url,
async () => {
const response : string | undefined = await RequestClientImpl.postText(url, data, headers);
return response as string | undefined;
},
retryPolicy
);
}
public static async deleteText (
url : string,
headers ?: {[key: string]: string},
retryPolicy ?: HttpRetryPolicy
) : Promise<string | undefined> {
url = this._prepareUrl(url);
return this._request(
'deleteText',
Method.DELETE,
url,
async () => {
const response : string | undefined = await RequestClientImpl.deleteText(url, headers);
return response as string | undefined;
},
retryPolicy
);
}
public static async getJsonEntity (
url : string,
headers ?: {[key: string]: string},
retryPolicy ?: HttpRetryPolicy
) : Promise<ResponseEntity<JsonAny|undefined> | undefined> {
url = this._prepareUrl(url);
return this._request(
'getJsonEntity',
Method.GET,
url,
async () => {
return await RequestClientImpl.getJsonEntity(url, headers);
},
retryPolicy
);
}
public static async postJsonEntity (
url : string,
data ?: ReadonlyJsonAny,
headers ?: {[key: string]: string},
retryPolicy ?: HttpRetryPolicy
) : Promise<ResponseEntity<JsonAny|undefined> | undefined> {
url = this._prepareUrl(url);
return this._request(
'postJsonEntity',
Method.POST,
url,
async () => {
return await RequestClientImpl.postJsonEntity(url, data as JsonAny, headers);
},
retryPolicy
);
}
public static async deleteJsonEntity (
url : string,
headers ?: {[key: string]: string},
retryPolicy ?: HttpRetryPolicy
) : Promise<ResponseEntity<JsonAny|undefined> | undefined> {
url = this._prepareUrl(url);
return this._request(
'deleteJsonEntity',
Method.DELETE,
url,
async () => {
return await RequestClientImpl.deleteJsonEntity(url, headers);
},
retryPolicy
);
}
public static async getTextEntity (
url : string,
headers ?: {[key: string]: string},
retryPolicy ?: HttpRetryPolicy
) : Promise<ResponseEntity<string|undefined> | undefined> {
url = this._prepareUrl(url);
return this._request(
'getTextEntity',
Method.GET,
url,
async () => {
return await RequestClientImpl.getTextEntity(url, headers);
},
retryPolicy
);
}
public static async postTextEntity (
url : string,
data ?: string,
headers ?: {[key: string]: string},
retryPolicy ?: HttpRetryPolicy
) : Promise<ResponseEntity<string|undefined> | undefined> {
url = this._prepareUrl(url);
return this._request(
'postTextEntity',
Method.POST,
url,
async () => {
return await RequestClientImpl.postTextEntity(url, data, headers);
},
retryPolicy
);
}
public static async deleteTextEntity (
url : string,
headers ?: {[key: string]: string},
retryPolicy ?: HttpRetryPolicy
) : Promise<ResponseEntity<string|undefined> | undefined> {
url = this._prepareUrl(url);
return this._request(
'deleteTextEntity',
Method.DELETE,
url,
async () => {
return await RequestClientImpl.deleteTextEntity(url, headers);
},
retryPolicy
);
}
}