@hyper-fetch/core 1.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (118) hide show
  1. package/.eslintrc.json +7 -0
  2. package/README.md +83 -0
  3. package/dist/builder/builder.constants.d.ts +9 -0
  4. package/dist/builder/builder.d.ts +141 -0
  5. package/dist/builder/builder.types.d.ts +45 -0
  6. package/dist/builder/builder.utils.d.ts +10 -0
  7. package/dist/builder/index.d.ts +4 -0
  8. package/dist/cache/cache.d.ts +76 -0
  9. package/dist/cache/cache.events.d.ts +28 -0
  10. package/dist/cache/cache.types.d.ts +49 -0
  11. package/dist/cache/cache.utils.d.ts +6 -0
  12. package/dist/cache/index.d.ts +4 -0
  13. package/dist/client/fetch.client.bindings.d.ts +25 -0
  14. package/dist/client/fetch.client.constants.d.ts +1 -0
  15. package/dist/client/fetch.client.d.ts +2 -0
  16. package/dist/client/fetch.client.types.d.ts +57 -0
  17. package/dist/client/fetch.client.utils.d.ts +5 -0
  18. package/dist/client/index.d.ts +5 -0
  19. package/dist/command/command.d.ts +87 -0
  20. package/dist/command/command.types.d.ts +196 -0
  21. package/dist/command/command.utils.d.ts +22 -0
  22. package/dist/command/index.d.ts +3 -0
  23. package/dist/constants/http.constants.d.ts +7 -0
  24. package/dist/constants/time.constants.d.ts +11 -0
  25. package/dist/dispatcher/dispatcher.constants.d.ts +6 -0
  26. package/dist/dispatcher/dispatcher.d.ts +155 -0
  27. package/dist/dispatcher/dispatcher.events.d.ts +11 -0
  28. package/dist/dispatcher/dispatcher.types.d.ts +31 -0
  29. package/dist/dispatcher/dispatcher.utils.d.ts +10 -0
  30. package/dist/dispatcher/index.d.ts +5 -0
  31. package/dist/effect/fetch.effect.d.ts +14 -0
  32. package/dist/effect/fetch.effect.types.d.ts +32 -0
  33. package/dist/effect/index.d.ts +2 -0
  34. package/dist/index.cjs.js +2 -0
  35. package/dist/index.cjs.js.map +7 -0
  36. package/dist/index.d.ts +10 -0
  37. package/dist/index.esm.js +2 -0
  38. package/dist/index.esm.js.map +7 -0
  39. package/dist/managers/app/app.manager.constants.d.ts +9 -0
  40. package/dist/managers/app/app.manager.d.ts +35 -0
  41. package/dist/managers/app/app.manager.events.d.ts +11 -0
  42. package/dist/managers/app/app.manager.types.d.ts +7 -0
  43. package/dist/managers/app/app.manager.utils.d.ts +4 -0
  44. package/dist/managers/app/index.d.ts +5 -0
  45. package/dist/managers/command/command.manager.d.ts +43 -0
  46. package/dist/managers/command/command.manager.events.d.ts +36 -0
  47. package/dist/managers/command/command.manager.types.d.ts +23 -0
  48. package/dist/managers/command/command.manager.utils.d.ts +16 -0
  49. package/dist/managers/command/index.d.ts +4 -0
  50. package/dist/managers/index.d.ts +3 -0
  51. package/dist/managers/logger/index.d.ts +4 -0
  52. package/dist/managers/logger/logger.manager.constants.d.ts +4 -0
  53. package/dist/managers/logger/logger.manager.d.ts +19 -0
  54. package/dist/managers/logger/logger.manager.types.d.ts +30 -0
  55. package/dist/managers/logger/logger.manager.utils.d.ts +3 -0
  56. package/dist/types/fetch.types.d.ts +15 -0
  57. package/dist/types/helpers.types.d.ts +11 -0
  58. package/dist/types/http.types.d.ts +1 -0
  59. package/dist/types/index.d.ts +3 -0
  60. package/dist/utils/index.d.ts +1 -0
  61. package/dist/utils/uuid.utils.d.ts +1 -0
  62. package/package.json +60 -0
  63. package/src/builder/builder.constants.ts +9 -0
  64. package/src/builder/builder.ts +309 -0
  65. package/src/builder/builder.types.ts +57 -0
  66. package/src/builder/builder.utils.ts +178 -0
  67. package/src/builder/index.ts +4 -0
  68. package/src/cache/cache.events.ts +44 -0
  69. package/src/cache/cache.ts +221 -0
  70. package/src/cache/cache.types.ts +56 -0
  71. package/src/cache/cache.utils.ts +29 -0
  72. package/src/cache/index.ts +4 -0
  73. package/src/client/fetch.client.bindings.ts +290 -0
  74. package/src/client/fetch.client.constants.ts +3 -0
  75. package/src/client/fetch.client.ts +98 -0
  76. package/src/client/fetch.client.types.ts +83 -0
  77. package/src/client/fetch.client.utils.ts +28 -0
  78. package/src/client/index.ts +5 -0
  79. package/src/command/command.ts +539 -0
  80. package/src/command/command.types.ts +268 -0
  81. package/src/command/command.utils.ts +179 -0
  82. package/src/command/index.ts +3 -0
  83. package/src/constants/http.constants.ts +7 -0
  84. package/src/constants/time.constants.ts +11 -0
  85. package/src/dispatcher/dispatcher.constants.ts +6 -0
  86. package/src/dispatcher/dispatcher.events.ts +42 -0
  87. package/src/dispatcher/dispatcher.ts +596 -0
  88. package/src/dispatcher/dispatcher.types.ts +39 -0
  89. package/src/dispatcher/dispatcher.utils.ts +55 -0
  90. package/src/dispatcher/index.ts +5 -0
  91. package/src/effect/fetch.effect.ts +28 -0
  92. package/src/effect/fetch.effect.types.ts +35 -0
  93. package/src/effect/index.ts +2 -0
  94. package/src/index.ts +12 -0
  95. package/src/managers/app/app.manager.constants.ts +24 -0
  96. package/src/managers/app/app.manager.events.ts +34 -0
  97. package/src/managers/app/app.manager.ts +74 -0
  98. package/src/managers/app/app.manager.types.ts +8 -0
  99. package/src/managers/app/app.manager.utils.ts +34 -0
  100. package/src/managers/app/index.ts +5 -0
  101. package/src/managers/command/command.manager.events.ts +212 -0
  102. package/src/managers/command/command.manager.ts +68 -0
  103. package/src/managers/command/command.manager.types.ts +25 -0
  104. package/src/managers/command/command.manager.utils.ts +19 -0
  105. package/src/managers/command/index.ts +4 -0
  106. package/src/managers/index.ts +3 -0
  107. package/src/managers/logger/index.ts +4 -0
  108. package/src/managers/logger/logger.manager.constants.ts +24 -0
  109. package/src/managers/logger/logger.manager.ts +70 -0
  110. package/src/managers/logger/logger.manager.types.ts +35 -0
  111. package/src/managers/logger/logger.manager.utils.ts +27 -0
  112. package/src/types/fetch.types.ts +39 -0
  113. package/src/types/helpers.types.ts +15 -0
  114. package/src/types/http.types.ts +1 -0
  115. package/src/types/index.ts +3 -0
  116. package/src/utils/index.ts +1 -0
  117. package/src/utils/uuid.utils.ts +3 -0
  118. package/tsconfig.json +8 -0
@@ -0,0 +1,596 @@
1
+ import EventEmitter from "events";
2
+
3
+ import {
4
+ DispatcherData,
5
+ getRequestType,
6
+ isFailedRequest,
7
+ canRetryRequest,
8
+ getDispatcherEvents,
9
+ DispatcherRequestType,
10
+ DispatcherOptionsType,
11
+ DispatcherStorageType,
12
+ DispatcherDumpValueType,
13
+ RunningRequestValueType,
14
+ } from "dispatcher";
15
+ import { BuilderInstance } from "builder";
16
+ import { getUniqueRequestId } from "utils";
17
+ import { CommandResponseDetails, LoggerType } from "managers";
18
+ import { CommandInstance, Command } from "command";
19
+ import { getErrorMessage } from "client";
20
+
21
+ /**
22
+ * Dispatcher class was made to store controlled request Fetches, and firing them all-at-once or one-by-one in command queue.
23
+ * Generally requests should be flushed at the same time, the queue provide mechanism to fire them in the order.
24
+ */
25
+ export class Dispatcher {
26
+ public emitter = new EventEmitter();
27
+ public events = getDispatcherEvents(this.emitter);
28
+ public storage: DispatcherStorageType = new Map<string, DispatcherData<CommandInstance>>();
29
+
30
+ private requestCount = new Map<string, number>();
31
+ private runningRequests = new Map<string, RunningRequestValueType[]>();
32
+
33
+ private logger: LoggerType;
34
+
35
+ constructor(public builder: BuilderInstance, public options?: DispatcherOptionsType) {
36
+ this.logger = builder.loggerManager.init("Dispatcher");
37
+
38
+ if (this.options?.storage) {
39
+ this.storage = this.options.storage;
40
+ }
41
+
42
+ // Going back from offline should re-trigger all requests
43
+ this.builder.appManager.events.onOnline(() => {
44
+ this.flush();
45
+ });
46
+
47
+ this.options?.onInitialization?.(this);
48
+ }
49
+
50
+ // ********************
51
+ // ********************
52
+ // Queue
53
+ // ********************
54
+ // ********************
55
+
56
+ /**
57
+ * Start request handling by queueKey
58
+ */
59
+ start = (queueKey: string) => {
60
+ // Change status to running
61
+ const queue = this.getQueue(queueKey);
62
+
63
+ // Start the queue when its stopped
64
+ queue.stopped = false;
65
+ this.setQueue(queueKey, queue);
66
+ this.flushQueue(queueKey);
67
+ this.events.setQueueStatus(queueKey, queue);
68
+ };
69
+
70
+ /**
71
+ * Pause request queue, but not cancel already started requests
72
+ */
73
+ pause = (queueKey: string) => {
74
+ // Change state to stopped
75
+ const queue = this.getQueue(queueKey);
76
+
77
+ queue.stopped = true;
78
+ this.setQueue(queueKey, queue);
79
+ this.events.setQueueStatus(queueKey, queue);
80
+ };
81
+
82
+ /**
83
+ * Stop request queue and cancel all started requests - those will be treated like not started
84
+ */
85
+ stop = (queueKey: string) => {
86
+ // Change state to stopped
87
+ const queue = this.getQueue(queueKey);
88
+
89
+ queue.stopped = true;
90
+ this.setQueue(queueKey, queue);
91
+
92
+ // Cancel running requests
93
+ this.cancelRunningRequests(queueKey);
94
+ this.events.setQueueStatus(queueKey, queue);
95
+ };
96
+
97
+ /**
98
+ * Return all
99
+ */
100
+ getQueuesKeys = () => {
101
+ return Array.from(this.storage.keys());
102
+ };
103
+
104
+ /**
105
+ * Return queue state object
106
+ */
107
+ getQueue = <Command extends CommandInstance = CommandInstance>(queueKey: string) => {
108
+ const initialQueueState: DispatcherData<Command> = { requests: [], stopped: false };
109
+ const storedEntity = this.storage.get<Command>(queueKey);
110
+
111
+ return storedEntity || initialQueueState;
112
+ };
113
+
114
+ /**
115
+ * Return request from queue state
116
+ */
117
+ getRequest = <Command extends CommandInstance = CommandInstance>(queueKey: string, requestId: string) => {
118
+ const initialQueueState: DispatcherData<Command> = { requests: [], stopped: false };
119
+ const storedEntity = this.storage.get<Command>(queueKey) || initialQueueState;
120
+
121
+ return storedEntity.requests.find((req) => req.requestId === requestId);
122
+ };
123
+
124
+ /**
125
+ * Get value of the active queue status based on the stopped status
126
+ */
127
+ getIsActiveQueue = (queueKey: string) => {
128
+ const queue = this.getQueue(queueKey);
129
+ const hasAvailableRequests = queue.requests.some((req) => !req.stopped);
130
+ const isRunningQueue = !queue.stopped;
131
+ return hasAvailableRequests && isRunningQueue;
132
+ };
133
+
134
+ /**
135
+ * Add new element to storage
136
+ */
137
+ addQueueElement = <Command extends CommandInstance = CommandInstance>(
138
+ queueKey: string,
139
+ dispatcherDump: DispatcherDumpValueType<Command>,
140
+ ) => {
141
+ const queue = this.getQueue<Command>(queueKey);
142
+ queue.requests.push(dispatcherDump);
143
+ this.setQueue<Command>(queueKey, queue);
144
+ };
145
+
146
+ /**
147
+ * Set new queue storage value
148
+ */
149
+ setQueue = <Command extends CommandInstance = CommandInstance>(queueKey: string, queue: DispatcherData<Command>) => {
150
+ this.storage.set<Command>(queueKey, queue);
151
+
152
+ // Emit Queue Changes
153
+ this.options?.onUpdateStorage?.(queueKey, queue);
154
+ this.events.setQueueChanged(queueKey, queue);
155
+
156
+ return queue;
157
+ };
158
+
159
+ /**
160
+ * Clear requests from queue cache
161
+ */
162
+ clearQueue = (queueKey: string) => {
163
+ const queue = this.getQueue(queueKey);
164
+ const newQueue = { requests: [], stopped: queue.stopped };
165
+ this.storage.set(queueKey, newQueue);
166
+
167
+ // Emit Queue Changes
168
+ this.options?.onDeleteFromStorage?.(queueKey, newQueue);
169
+ this.events.setQueueChanged(queueKey, newQueue);
170
+
171
+ return newQueue;
172
+ };
173
+
174
+ /**
175
+ * Method used to flush the queue requests
176
+ */
177
+ flushQueue = async (queueKey: string) => {
178
+ const queue = this.getQueue(queueKey);
179
+ const runningRequests = this.getRunningRequests(queueKey);
180
+ const queueElement = queue.requests.find((request) => !request.stopped);
181
+
182
+ const isStopped = queue && queue.stopped;
183
+ const isOffline = !this.builder.appManager.isOnline;
184
+ const isConcurrent = !queueElement?.commandDump.queued;
185
+ const isInactive = !runningRequests.length;
186
+ const isEmpty = !queueElement;
187
+
188
+ // When there are no requests to flush, when its stopped, there is running request
189
+ // or there is no request to trigger - we don't want to perform actions
190
+ if (isStopped || isOffline || isEmpty) {
191
+ this.logger.debug("Skipping queue trigger", { isStopped, isOffline, isEmpty });
192
+ } else if (isConcurrent) {
193
+ queue.requests.forEach((element) => {
194
+ if (!this.hasRunningRequest(queueKey, element.requestId)) {
195
+ this.performRequest(element);
196
+ }
197
+ });
198
+ } else if (isInactive) {
199
+ await this.performRequest(queueElement);
200
+ this.flushQueue(queueKey);
201
+ }
202
+ };
203
+
204
+ /**
205
+ * Flush all available requests from all queues
206
+ */
207
+ flush = async () => {
208
+ const keys = this.getQueuesKeys();
209
+
210
+ // eslint-disable-next-line no-restricted-syntax
211
+ for (const key of keys) {
212
+ const storageElement = this.getQueue(key);
213
+
214
+ if (storageElement) {
215
+ this.flushQueue(key);
216
+ }
217
+ }
218
+ };
219
+
220
+ /**
221
+ * Clear all running requests and storage
222
+ */
223
+ clear = () => {
224
+ const keys = this.getQueuesKeys();
225
+ keys.forEach((queueKey) => this.cancelRunningRequests(queueKey));
226
+
227
+ this.runningRequests.clear();
228
+ this.storage.clear();
229
+ this.options?.onClearStorage?.(this);
230
+ };
231
+
232
+ // ********************
233
+ // ********************
234
+ // Requests
235
+ // ********************
236
+ // ********************
237
+
238
+ /**
239
+ * Start particular request
240
+ */
241
+ startRequest = (queueKey: string, requestId: string) => {
242
+ // Change status to running
243
+ const queue = this.getQueue(queueKey);
244
+ const request = queue.requests.find((element) => element.requestId === requestId);
245
+
246
+ // Start the queue when its stopped
247
+ if (request) {
248
+ request.stopped = false;
249
+ this.setQueue(queueKey, queue);
250
+ this.flushQueue(queueKey);
251
+ this.events.setQueueStatus(queueKey, queue);
252
+ }
253
+ };
254
+
255
+ /**
256
+ * Stop particular request
257
+ */
258
+ stopRequest = (queueKey: string, requestId: string) => {
259
+ // Change state to stopped
260
+ const queue = this.getQueue(queueKey);
261
+ const request = queue.requests.find((element) => element.requestId === requestId);
262
+
263
+ if (request) {
264
+ request.stopped = true;
265
+ this.setQueue(queueKey, queue);
266
+
267
+ // Cancel running requests
268
+ this.cancelRunningRequest(queueKey, requestId);
269
+ this.events.setQueueStatus(queueKey, queue);
270
+ }
271
+ };
272
+
273
+ /**
274
+ * Get currently running requests from all queueKeys
275
+ */
276
+ getAllRunningRequest = () => {
277
+ return Array.from(this.runningRequests.values()).flat();
278
+ };
279
+
280
+ /**
281
+ * Get currently running requests
282
+ */
283
+ getRunningRequests = (queueKey: string) => {
284
+ return this.runningRequests.get(queueKey) || [];
285
+ };
286
+
287
+ /**
288
+ * Get running request by id
289
+ */
290
+ getRunningRequest = (queueKey: string, requestId: string) => {
291
+ const runningRequests = this.getRunningRequests(queueKey);
292
+ return runningRequests.find((req) => req.requestId === requestId);
293
+ };
294
+
295
+ /**
296
+ * Add request to the running requests list
297
+ */
298
+ addRunningRequest = (queueKey: string, requestId: string, command: CommandInstance) => {
299
+ const runningRequests = this.getRunningRequests(queueKey);
300
+ runningRequests.push({ requestId, command });
301
+ this.runningRequests.set(queueKey, runningRequests);
302
+ };
303
+
304
+ /**
305
+ * Get the value based on the currently running requests
306
+ */
307
+ hasRunningRequests = (queueKey: string) => {
308
+ return !!this.getRunningRequests(queueKey).length;
309
+ };
310
+
311
+ /**
312
+ * Check if request is currently processing
313
+ */
314
+ hasRunningRequest = (queueKey: string, requestId: string) => {
315
+ const runningRequests = this.getRunningRequests(queueKey);
316
+ return !!runningRequests.find((req) => req.requestId === requestId);
317
+ };
318
+
319
+ /**
320
+ * Cancel all started requests, but do NOT remove it from main storage
321
+ */
322
+ cancelRunningRequests = (queueKey: string) => {
323
+ this.runningRequests.get(queueKey)?.forEach((request) => {
324
+ this.builder.commandManager.abortByRequestId(request.command.abortKey, request.requestId);
325
+ });
326
+ this.deleteRunningRequests(queueKey);
327
+ };
328
+ /**
329
+ * Cancel started request, but do NOT remove it from main storage
330
+ */
331
+ cancelRunningRequest = (queueKey: string, requestId: string) => {
332
+ const requests = this.getRunningRequests(queueKey).filter((request) => {
333
+ if (request.requestId === requestId) {
334
+ this.builder.commandManager.abortByRequestId(request.command.abortKey, request.requestId);
335
+ return false;
336
+ }
337
+ return true;
338
+ });
339
+
340
+ this.runningRequests.set(queueKey, requests);
341
+ };
342
+
343
+ /**
344
+ * Delete all started requests, but do NOT clear it from queue and do NOT cancel them
345
+ */
346
+ deleteRunningRequests = (queueKey: string) => {
347
+ this.runningRequests.set(queueKey, []);
348
+ };
349
+
350
+ /**
351
+ * Delete request by id, but do NOT clear it from queue and do NOT cancel them
352
+ */
353
+ deleteRunningRequest = (queueKey: string, requestId: string) => {
354
+ const runningRequests = this.getRunningRequests(queueKey);
355
+ this.runningRequests.set(
356
+ queueKey,
357
+ runningRequests.filter((req) => req.requestId !== requestId),
358
+ );
359
+ };
360
+
361
+ /**
362
+ * Get count of requests from the same queueKey
363
+ */
364
+ getQueueRequestCount = (queueKey: string) => {
365
+ return this.requestCount.get(queueKey) || 0;
366
+ };
367
+
368
+ /**
369
+ * Add request count to the queueKey
370
+ */
371
+ incrementQueueRequestCount = (queueKey: string) => {
372
+ const count = this.requestCount.get(queueKey) || 0;
373
+ this.requestCount.set(queueKey, count + 1);
374
+ };
375
+
376
+ /**
377
+ * Create storage element from command
378
+ */
379
+ // eslint-disable-next-line class-methods-use-this
380
+ createStorageElement = <Command extends CommandInstance>(command: Command) => {
381
+ const requestId = getUniqueRequestId(command.queueKey);
382
+ const storageElement: DispatcherDumpValueType<Command> = {
383
+ requestId,
384
+ timestamp: +new Date(),
385
+ commandDump: command.dump(),
386
+ retries: 0,
387
+ stopped: false,
388
+ };
389
+ return storageElement;
390
+ };
391
+
392
+ // ********************
393
+ // ********************
394
+ // Dispatching
395
+ // ********************
396
+ // ********************
397
+
398
+ /**
399
+ * Add command to the dispatcher handler
400
+ */
401
+ add = (command: CommandInstance) => {
402
+ const { queueKey } = command;
403
+
404
+ // Create dump of the request to allow storing it in localStorage, AsyncStorage or any other
405
+ // This way we don't save the Class but the instruction of the request to be done
406
+ const storageElement = this.createStorageElement(command);
407
+ const { requestId } = storageElement;
408
+
409
+ const queue = this.getQueue(queueKey);
410
+ const [latestRequest] = queue.requests.slice(-1);
411
+ const requestType = getRequestType(command, latestRequest);
412
+
413
+ this.logger.debug("Adding request to queue", { requestType, command, requestId });
414
+
415
+ switch (requestType) {
416
+ case DispatcherRequestType.oneByOne: {
417
+ // Requests will go one by one
418
+ this.addQueueElement(queueKey, storageElement);
419
+ this.flushQueue(queueKey);
420
+ return requestId;
421
+ }
422
+ case DispatcherRequestType.previousCanceled: {
423
+ // Cancel all previous on-going requests
424
+ this.cancelRunningRequests(queueKey);
425
+ this.clearQueue(queueKey);
426
+ this.addQueueElement(queueKey, storageElement);
427
+ this.flushQueue(queueKey);
428
+ return requestId;
429
+ }
430
+ case DispatcherRequestType.deduplicated: {
431
+ // Return the running requestId to fullfil the events
432
+ return queue.requests[0].requestId;
433
+ }
434
+ default: {
435
+ this.addQueueElement(queueKey, storageElement);
436
+ this.flushQueue(queueKey);
437
+ return requestId;
438
+ }
439
+ }
440
+ };
441
+
442
+ /**
443
+ * Delete from the storage and cancel request
444
+ */
445
+ delete = (queueKey: string, requestId: string, abortKey: string) => {
446
+ this.logger.debug("Deleting request", { queueKey, requestId, abortKey });
447
+ const queue = this.getQueue(queueKey);
448
+ const request = queue.requests.find((req) => req.requestId === requestId);
449
+
450
+ if (!request) return;
451
+
452
+ const command = new Command(this.builder, request.commandDump.commandOptions, request.commandDump);
453
+ queue.requests = queue.requests.filter((req) => req.requestId !== requestId);
454
+ this.storage.set(queueKey, queue);
455
+
456
+ // Clean controllers
457
+ if (this.hasRunningRequest(queueKey, requestId)) {
458
+ this.deleteRunningRequest(queueKey, requestId);
459
+ this.builder.commandManager.abortByRequestId(abortKey, requestId);
460
+ }
461
+
462
+ // Emit Queue Changes
463
+ this.options?.onDeleteFromStorage?.(queueKey, queue);
464
+ this.events.setQueueChanged(queueKey, queue);
465
+ this.builder.commandManager.events.emitRemove(queueKey, requestId, { requestId, command });
466
+
467
+ if (!queue.requests.length) {
468
+ this.events.setDrained(queueKey, queue);
469
+ }
470
+
471
+ return queue;
472
+ };
473
+
474
+ /**
475
+ * Request can run for some time, once it's done, we have to check if it's successful or if it was aborted
476
+ * It can be different once the previous call was set as cancelled and removed from queue before this request got resolved
477
+ */
478
+ performRequest = async (storageElement: DispatcherDumpValueType) => {
479
+ const command = new Command(this.builder, storageElement.commandDump.commandOptions, storageElement.commandDump);
480
+ const { commandDump, requestId } = storageElement;
481
+ this.logger.info("Performing request", { command, requestId });
482
+
483
+ const { retry, retryTime, queueKey, cacheKey, abortKey, offline } = commandDump;
484
+ const { client, commandManager, cache, appManager } = this.builder;
485
+
486
+ const canRetry = canRetryRequest(storageElement.retries, retry);
487
+ // When offline not perform any request
488
+ const isOffline = !appManager.isOnline && offline;
489
+ // When request with this id was triggered again
490
+ const isAlreadyRunning = this.hasRunningRequest(queueKey, requestId);
491
+ const isStopped = storageElement.stopped;
492
+
493
+ if (isOffline || isAlreadyRunning || isStopped) {
494
+ return this.logger.warning("Unable to perform request", { isOffline, isAlreadyRunning, isStopped });
495
+ }
496
+
497
+ // Additionally keep the running request to possibly abort it later
498
+ this.addRunningRequest(queueKey, requestId, command);
499
+
500
+ // Propagate the loading to all connected hooks
501
+ commandManager.events.emitLoading(queueKey, requestId, {
502
+ queueKey,
503
+ requestId,
504
+ loading: true,
505
+ isRetry: !!storageElement.retries,
506
+ isOffline,
507
+ });
508
+
509
+ // Trigger Request
510
+ this.incrementQueueRequestCount(queueKey);
511
+
512
+ const response = await client(command, requestId);
513
+
514
+ // Do not continue the request handling when it got stopped and request was unsuccessful
515
+ // Or when the request was aborted/canceled
516
+ const isOfflineResponseStatus = !appManager.isOnline;
517
+ // Request is failed when there is the error message or the status is 0 or equal/bigger than 400
518
+ const isFailed = isFailedRequest(response);
519
+ // If there is no running request with this id, it means it was cancelled and removed during send
520
+ const isCancelMessage = getErrorMessage("abort").message === response[1]?.message;
521
+ const isCanceled = !this.hasRunningRequest(queueKey, requestId) || isCancelMessage;
522
+
523
+ // Remove running request, must be called after isCancelled
524
+ this.deleteRunningRequest(queueKey, requestId);
525
+
526
+ const requestDetails: CommandResponseDetails = {
527
+ isFailed,
528
+ isCanceled,
529
+ isOffline: isOfflineResponseStatus,
530
+ retries: storageElement.retries,
531
+ timestamp: +new Date(),
532
+ };
533
+
534
+ // Turn off loading
535
+ commandManager.events.emitLoading(queueKey, requestId, {
536
+ queueKey,
537
+ requestId,
538
+ loading: false,
539
+ isRetry: !!storageElement.retries,
540
+ isOffline,
541
+ });
542
+ // Global response emitter to handle command execution
543
+ commandManager.events.emitResponse(cacheKey, requestId, response, requestDetails);
544
+ // Cache event to emit the data inside and store it
545
+ cache.set(command, response, requestDetails);
546
+ this.logger.info("Request finished", { requestId, command, response, requestDetails });
547
+
548
+ // On cancelled
549
+ if (isCanceled) {
550
+ const queue = this.getQueue(queueKey);
551
+ const request = queue.requests.find((req) => req.requestId === requestId);
552
+
553
+ // do not remove cancelled request as it may be result of manual queue pause
554
+ // if abort was done without stop action we can remove request
555
+ if (!queue.stopped && !request?.stopped) {
556
+ this.logger.debug("Request paused", { response, requestDetails, command });
557
+ return this.delete(queueKey, requestId, abortKey);
558
+ }
559
+ return this.logger.debug("Request canceled", { response, requestDetails, command });
560
+ }
561
+ // On offline
562
+ if (isFailed && isOfflineResponseStatus) {
563
+ // if we don't want to keep offline request - just delete them
564
+ if (!offline) {
565
+ this.logger.warning("Removing non-offline request", { response, requestDetails, command });
566
+ return this.delete(queueKey, requestId, abortKey);
567
+ }
568
+ // do not remove request from store as we want to re-send it later
569
+ return this.logger.debug("Awaiting for network restoration", { response, requestDetails, command });
570
+ }
571
+ // On success
572
+ if (!isFailed) {
573
+ this.delete(queueKey, requestId, abortKey);
574
+ return this.logger.debug("Successful response, removing request from queue.", {
575
+ response,
576
+ requestDetails,
577
+ command,
578
+ });
579
+ }
580
+ // On retry
581
+ if (isFailed && canRetry) {
582
+ this.logger.debug("Waiting for retry", { response, requestDetails, command });
583
+ // Perform retry once request is failed
584
+ setTimeout(() => {
585
+ this.logger.warning("Error response, performing retry");
586
+ this.performRequest({
587
+ ...storageElement,
588
+ retries: storageElement.retries + 1,
589
+ });
590
+ }, retryTime || 0);
591
+ } else {
592
+ this.logger.error("All retries have been used. Removing request from queue.");
593
+ this.delete(queueKey, requestId, abortKey);
594
+ }
595
+ };
596
+ }
@@ -0,0 +1,39 @@
1
+ import { Dispatcher } from "dispatcher";
2
+ import { CommandDump, CommandInstance } from "command";
3
+
4
+ export type DispatcherOptionsType = {
5
+ storage?: DispatcherStorageType;
6
+ onInitialization?: (dispatcherInstance: Dispatcher) => void;
7
+ onUpdateStorage?: <Command extends CommandInstance>(queueKey: string, data: DispatcherData<Command>) => void;
8
+ onDeleteFromStorage?: <Command extends CommandInstance>(queueKey: string, data: DispatcherData<Command>) => void;
9
+ onClearStorage?: (dispatcherInstance: Dispatcher) => void;
10
+ };
11
+
12
+ // Values
13
+ export type DispatcherDumpValueType<Command extends CommandInstance = CommandInstance> = {
14
+ requestId: string;
15
+ commandDump: CommandDump<Command>;
16
+ retries: number;
17
+ timestamp: number;
18
+ stopped: boolean;
19
+ };
20
+ export type DispatcherData<Command extends CommandInstance = CommandInstance> = {
21
+ requests: DispatcherDumpValueType<Command>[];
22
+ stopped: boolean;
23
+ };
24
+
25
+ // Storage
26
+ export type DispatcherStorageType = {
27
+ set: <Command extends CommandInstance = CommandInstance>(key: string, data: DispatcherData<Command>) => void;
28
+ get: <Command extends CommandInstance = CommandInstance>(key: string) => DispatcherData<Command> | undefined;
29
+ keys: () => string[] | IterableIterator<string>;
30
+ delete: (key: string) => void;
31
+ clear: () => void;
32
+ };
33
+
34
+ // Running
35
+
36
+ export type RunningRequestValueType = {
37
+ requestId: string;
38
+ command: CommandInstance;
39
+ };
@@ -0,0 +1,55 @@
1
+ import { CommandInstance } from "command";
2
+ import { ClientResponseType } from "client";
3
+ import { DispatcherRequestType, DispatcherDumpValueType } from "dispatcher";
4
+
5
+ // Events
6
+
7
+ export const getDispatcherDrainedEventKey = (key: string): string => {
8
+ return `${key}-drained-event`;
9
+ };
10
+ export const getDispatcherStatusEventKey = (key: string): string => {
11
+ return `${key}-status-event`;
12
+ };
13
+ export const getDispatcherChangeEventKey = (key: string): string => {
14
+ return `${key}-change-event`;
15
+ };
16
+
17
+ // Requesting
18
+
19
+ export const getIsEqualTimestamp = (currentTimestamp: number, threshold: number, queueTimestamp?: number): boolean => {
20
+ if (!queueTimestamp) {
21
+ return false;
22
+ }
23
+ return queueTimestamp - currentTimestamp <= threshold;
24
+ };
25
+
26
+ export const canRetryRequest = (currentRetries: number, retry: number | undefined) => {
27
+ if (retry && currentRetries < retry) {
28
+ return true;
29
+ }
30
+ return false;
31
+ };
32
+
33
+ export const getRequestType = (command: CommandInstance, latestRequest: DispatcherDumpValueType | undefined) => {
34
+ const { queued, cancelable, deduplicate } = command;
35
+ const canDeduplicate = latestRequest ? +new Date() - latestRequest.timestamp <= command.deduplicateTime : false;
36
+
37
+ if (queued) {
38
+ return DispatcherRequestType.oneByOne;
39
+ }
40
+ if (cancelable) {
41
+ return DispatcherRequestType.previousCanceled;
42
+ }
43
+ if (canDeduplicate && deduplicate) {
44
+ return DispatcherRequestType.deduplicated;
45
+ }
46
+ return DispatcherRequestType.allAtOnce;
47
+ };
48
+
49
+ export const isFailedRequest = (data: ClientResponseType<unknown, unknown>) => {
50
+ const [, , status] = data;
51
+ if (!status || status >= 400) {
52
+ return true;
53
+ }
54
+ return false;
55
+ };
@@ -0,0 +1,5 @@
1
+ export * from "./dispatcher.constants";
2
+ export * from "./dispatcher.events";
3
+ export * from "./dispatcher";
4
+ export * from "./dispatcher.types";
5
+ export * from "./dispatcher.utils";