-
Notifications
You must be signed in to change notification settings - Fork 0
/
mod.ts
727 lines (727 loc) · 23.4 KB
/
mod.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
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
import { randomInt } from "node:crypto";
import {
HTTPHeaderLink,
type HTTPHeaderLinkEntry
} from "https://raw.githubusercontent.com/hugoalh/http-header-link-es/v1.0.3/mod.ts";
import { HTTPHeaderRetryAfter } from "https://raw.githubusercontent.com/hugoalh/http-header-retry-after-es/v1.1.0/mod.ts";
import { slug } from "./_slug.ts";
const httpStatusCodesRedirectable: Set<number> = new Set<number>([
301,
302,
303,
307,
308
]);
const httpStatusCodesRetryable: Set<number> = new Set<number>([
408,
429,
500,
502,
503,
504,
506,
507,
508
]);
/**
* exFetch default user agent.
*/
export const userAgentDefault: string = `${slug} exFetch/0.6.0`;
/**
* exFetch delay options.
*/
export interface ExFetchDelayOptions {
/**
* Maximum time per delay, by milliseconds.
*/
maximum?: number;
/**
* Minimum time per delay, by milliseconds.
*/
minimum?: number;
}
type ExFetchDelayOptionsInternal = Required<ExFetchDelayOptions>;
/**
* exFetch event common payload.
*/
export interface ExFetchEventCommonPayload {
/**
* Status code of the current response.
*/
statusCode: Response["status"];
/**
* Status text of the current response.
*/
statusText: Response["statusText"];
}
/**
* exFetch paginate event payload.
*/
export interface ExFetchEventPaginatePayload {
/**
* Current count of the paginates, begin from `1`.
*/
countCurrent: number;
/**
* Maximum number of the paginates allowed.
*/
countMaximum: number;
/**
* Will paginate to the next page after this amount of time, by milliseconds.
*/
paginateAfter: number;
/**
* Will paginate to this URL.
*/
paginateURL: URL;
}
/**
* exFetch redirect event payload.
*/
export interface ExFetchEventRedirectPayload extends ExFetchEventCommonPayload {
/**
* Current count of the redirects, begin from `1`.
*/
countCurrent: number;
/**
* Maximum number of the redirects allowed.
*/
countMaximum: number;
/**
* Will redirect after this amount of time, by milliseconds.
*/
redirectAfter: number;
/**
* Will redirect to this URL.
*/
redirectURL: URL;
}
/**
* exFetch retry event payload.
*/
export interface ExFetchEventRetryPayload extends ExFetchEventCommonPayload {
/**
* Current count of the retries, begin from `1`.
*/
countCurrent: number;
/**
* Maximum number of the retries allowed.
*/
countMaximum: number;
/**
* Will retry after this amount of time, by milliseconds.
*/
retryAfter: number;
/**
* Will retry this URL.
*/
retryURL: URL;
}
/**
* exFetch paginate link up payload.
*/
export interface ExFetchPaginateLinkUpPayload {
/**
* Header link of the current page.
*/
currentHeaderLink: HTTPHeaderLink;
/**
* URL of the current page.
*/
currentURL: URL;
}
/**
* exFetch paginate options.
*/
export interface ExFetchPaginateOptions {
/**
* Amount of time to delay between the paginates, by milliseconds.
* @default 0
*/
delay?: number | ExFetchDelayOptions;
/**
* Custom function for correctly link up to the next page, useful for the endpoints which not correctly return an absolute or relative URL.
* @param {ExFetchPaginateLinkUpPayload} param Link up payload of the paginate.
* @returns {URL | null | undefined} URL of the next page.
*/
linkUpNextPage?(param: ExFetchPaginateLinkUpPayload): URL | null | undefined;
/**
* Maximum amount of paginates to allow.
* @default Infinity // Unlimited
*/
maximum?: number;
/**
* Event listener for the paginates.
* @param {ExFetchEventPaginatePayload} param Event payload of the paginate.
* @returns {void}
*/
onEvent?(param: ExFetchEventPaginatePayload): void;
/**
* Whether to throw an error when the latest page response provide an invalid HTTP header `Link`.
* @default true
*/
throwOnInvalidHeaderLink?: boolean;
}
interface ExFetchPaginateOptionsInternal extends Required<Omit<ExFetchPaginateOptions, "delay" | "onEvent">>, Pick<ExFetchPaginateOptions, "onEvent"> {
/**
* Amount of time to delay between the paginates, by milliseconds.
*/
delay: ExFetchDelayOptionsInternal;
}
/**
* exFetch redirect options.
*/
export interface ExFetchRedirectOptions {
/**
* Amount of time to delay between the redirects, by milliseconds.
* @default 0
*/
delay?: number | ExFetchDelayOptions;
/**
* Maximum amount of redirects to allow.
* @default Infinity
*/
maximum?: number;
/**
* Event listener for the redirects.
* @param {ExFetchEventRedirectPayload} param Event payload of the redirect.
* @returns {void}
*/
onEvent?(param: ExFetchEventRedirectPayload): void;
}
interface ExFetchRedirectOptionsInternal extends Required<Omit<ExFetchRedirectOptions, "delay" | "onEvent">>, Pick<ExFetchRedirectOptions, "onEvent"> {
/**
* Amount of time to delay between the redirects, by milliseconds.
*/
delay: ExFetchDelayOptionsInternal;
}
/**
* exFetch retry options.
*/
export interface ExFetchRetryOptions {
/**
* Amount of time to delay between the attempts, by milliseconds. This only apply when the endpoint have not provide any retry information in the response.
* @default
* {
* maximum: 60000,
* minimum: 1000
* }
*/
delay?: number | ExFetchDelayOptions;
/**
* Maximum amount of attempts to allow.
* @default 4
*/
maximum?: number;
/**
* Event listener for the retries.
* @param {ExFetchEventRetryPayload} param Event payload of the retry.
* @returns {void}
*/
onEvent?(param: ExFetchEventRetryPayload): void;
}
interface ExFetchRetryOptionsInternal extends Required<Omit<ExFetchRetryOptions, "delay" | "onEvent">>, Pick<ExFetchRetryOptions, "onEvent"> {
/**
* Amount of time to delay between the attempts, by milliseconds. This only apply when the endpoint have not provide any retry information in the response.
*/
delay: ExFetchDelayOptionsInternal;
}
/**
* exFetch options.
*/
export interface ExFetchOptions {
/**
* **\[🧪 Experimental\]** Whether to cache suitable `Request`-`Response`s.
*
* - `false`: Disable cache.
* - `true`: Enable cache with default name, manage automatically.
* - `<string>`: Enable cache with custom name, manage automatically.
* - `<Cache>`: Enable cache, manage manually.
* @default {false}
*/
cacheStorage?: boolean | string | Cache;
/**
* Custom HTTP status codes that retryable.
*
* This will override the default when defined; To add or delete some of the HTTP status codes, use methods {@linkcode ExFetch.addHTTPStatusCodeRetryable} or {@linkcode ExFetch.deleteHTTPStatusCodeRetryable} instead.
* @default {undefined}
*/
httpStatusCodesRetryable?: number[] | Set<number>;
/**
* Paginate options.
*/
paginate?: ExFetchPaginateOptions;
/**
* Redirect options. This only apply when define property `redirect` as `"follow"` in the request, and define property `maximum` in this option.
*/
redirect?: ExFetchRedirectOptions;
/**
* Retry options.
*/
retry?: ExFetchRetryOptions;
/**
* Timeout of the request (include the redirects and the retries), by milliseconds. This only apply when have not define property `signal` in the request.
* @default Infinity // Disable
*/
timeout?: number;
/**
* Custom user agent. This only apply when have not define HTTP header `User-Agent` in the request.
* @default `${RuntimeSlug} exFetch/${ExFetchVersion}`.
*/
userAgent?: string;
}
function resolveDelayOptions(parameterName: string, input: number | ExFetchDelayOptions, original: ExFetchDelayOptionsInternal): ExFetchDelayOptionsInternal {
if (typeof input === "number") {
if (!(Number.isSafeInteger(input) && input >= 0)) {
throw new RangeError(`\`${input}\` (parameter \`${parameterName}\`) is not a number which is integer, positive, and safe!`);
}
return {
maximum: input,
minimum: input
};
}
const optionsResolve: ExFetchDelayOptionsInternal = { ...original };
if (typeof input.maximum !== "undefined") {
if (!(Number.isSafeInteger(input.maximum) && input.maximum >= 0)) {
throw new RangeError(`\`${input.maximum}\` (parameter \`${parameterName}.maximum\`) is not a number which is integer, positive, and safe!`);
}
optionsResolve.maximum = input.maximum;
}
if (typeof input.minimum !== "undefined") {
if (!(Number.isSafeInteger(input.minimum) && input.minimum >= 0)) {
throw new RangeError(`\`${input.minimum}\` (parameter \`${parameterName}.minimum\`) is not a number which is integer, positive, and safe!`);
}
optionsResolve.minimum = input.minimum;
}
if (optionsResolve.minimum > optionsResolve.maximum) {
throw new RangeError(`\`${optionsResolve.minimum}\` (parameter \`${parameterName}.minimum\`) is large than \`${optionsResolve.maximum}\` (parameter \`${parameterName}.maximum\`)!`);
}
return optionsResolve;
}
function resolveDelayTime({
maximum,
minimum
}: ExFetchDelayOptionsInternal): number {
if (maximum === minimum) {
return maximum;
}
return randomInt(minimum, maximum + 1);
}
/**
* Start a `Promise` based delay with `AbortSignal`.
* @param {number} value Time of the delay, by milliseconds. `0` means execute "immediately", or more accurately, the next event cycle.
* @param {AbortSignal} [signal] A signal object that allow to communicate with a DOM request and abort it if required via an `AbortController` object.
* @returns {Promise<void>}
*/
function setDelay(value: number, signal?: AbortSignal): Promise<void> {
if (value <= 0) {
return Promise.resolve();
}
if (signal?.aborted) {
return Promise.reject(signal.reason);
}
return new Promise((resolve, reject): void => {
function abort(): void {
clearTimeout(id);
reject(signal?.reason);
}
function done(): void {
signal?.removeEventListener("abort", abort);
resolve();
}
const id: number = setTimeout(done, value);
signal?.addEventListener("abort", abort, { once: true });
});
}
/**
* Extend `fetch`.
*
* > **🛡️ Permissions**
* >
* > | **Target** | **Type** | **Coverage** |
* > |:--|:--|:--|
* > | Deno | Network (`allow-net`) | Resource |
*/
export class ExFetch {
#cacheStorage?: Cache;
#cacheStorageDefer?: Promise<Cache>;
#httpStatusCodesRetryable: Set<number>;
#paginate: ExFetchPaginateOptionsInternal = {
delay: {
maximum: 0,
minimum: 0
},
linkUpNextPage: ({ currentHeaderLink, currentURL }: ExFetchPaginateLinkUpPayload): URL | null | undefined => {
const currentHeaderLinkEntryNextPage: HTTPHeaderLinkEntry[] = currentHeaderLink.getByRel("next");
if (currentHeaderLinkEntryNextPage.length > 0) {
return new URL(currentHeaderLinkEntryNextPage[0][0], currentURL);
}
return;
},
maximum: Infinity,
onEvent: undefined,
throwOnInvalidHeaderLink: true
};
#redirect: ExFetchRedirectOptionsInternal = {
delay: {
maximum: 0,
minimum: 0
},
maximum: Infinity,
onEvent: undefined
};
#retry: ExFetchRetryOptionsInternal = {
delay: {
maximum: 60000,
minimum: 1000
},
maximum: 4,
onEvent: undefined
};
#timeout = Infinity;
#userAgent: string;
/**
* @access private
* @param {string} parameterName Name of the parameter.
* @param {ExFetchPaginateOptions} input
* @returns {ExFetchPaginateOptionsInternal}
*/
#resolvePaginateOptions(parameterName: string, input: ExFetchPaginateOptions): ExFetchPaginateOptionsInternal {
const optionsResolve: ExFetchPaginateOptionsInternal = { ...this.#paginate };
if (typeof input.delay !== "undefined") {
optionsResolve.delay = resolveDelayOptions(`${parameterName}.delay`, input.delay, this.#paginate.delay);
}
if (typeof input.linkUpNextPage !== "undefined") {
optionsResolve.linkUpNextPage = input.linkUpNextPage;
}
if (typeof input.maximum !== "undefined") {
if (input.maximum !== Infinity && !(Number.isSafeInteger(input.maximum) && input.maximum > 0)) {
throw new RangeError(`\`${input.maximum}\` (parameter \`${parameterName}.maximum\`) is not \`Infinity\`, or a number which is integer, safe, and > 0!`);
}
optionsResolve.maximum = input.maximum;
}
if (typeof input.onEvent !== "undefined") {
optionsResolve.onEvent = input.onEvent;
}
if (typeof input.throwOnInvalidHeaderLink !== "undefined") {
optionsResolve.throwOnInvalidHeaderLink = input.throwOnInvalidHeaderLink;
}
return optionsResolve;
}
/**
* Create a new extend `fetch` instance.
*
* > **🛡️ Permissions**
* >
* > | **Target** | **Type** | **Coverage** |
* > |:--|:--|:--|
* > | Deno | Network (`allow-net`) | Resource |
* @param {ExFetchOptions} [options={}] Options.
*/
constructor(options: ExFetchOptions = {}) {
if (typeof globalThis.Cache !== "undefined") {
if (options.cacheStorage instanceof globalThis.Cache) {
this.#cacheStorage = options.cacheStorage;
} else if (typeof options.cacheStorage === "boolean") {
if (options.cacheStorage) {
this.#cacheStorageDefer = globalThis.caches.open("exFetch");
}
} else if (typeof options.cacheStorage !== "undefined") {
this.#cacheStorageDefer = globalThis.caches.open(options.cacheStorage);
}
}
this.#httpStatusCodesRetryable = new Set<number>(options.httpStatusCodesRetryable ?? httpStatusCodesRetryable);
this.#paginate = this.#resolvePaginateOptions("options.paginate", options.paginate ?? {});
if (typeof options.redirect?.delay !== "undefined") {
this.#redirect.delay = resolveDelayOptions("options.redirect.delay", options.redirect.delay, this.#redirect.delay);
}
if (typeof options.redirect?.maximum !== "undefined") {
if (!(Number.isSafeInteger(options.redirect.maximum) && options.redirect.maximum >= 0)) {
throw new RangeError(`\`${options.redirect.maximum}\` (parameter \`options.redirect.maximum\`) is not a number which is integer, positive, and safe!`);
}
this.#redirect.maximum = options.redirect.maximum;
}
this.#redirect.onEvent = options.redirect?.onEvent;
if (typeof options.retry?.delay !== "undefined") {
this.#retry.delay = resolveDelayOptions("options.retry.delay", options.retry.delay, this.#retry.delay);
}
if (typeof options.retry?.maximum !== "undefined") {
if (!(Number.isSafeInteger(options.retry.maximum) && options.retry.maximum >= 0)) {
throw new RangeError(`\`${options.retry.maximum}\` (parameter \`options.retry.maximum\`) is not a number which is integer, positive, and safe!`);
}
this.#retry.maximum = options.retry.maximum;
}
this.#retry.onEvent = options.retry?.onEvent;
if (typeof options.timeout !== "undefined") {
if (options.timeout !== Infinity && !(Number.isSafeInteger(options.timeout) && options.timeout > 0)) {
throw new RangeError(`\`${options.timeout}\` (parameter \`options.timeout\`) is not \`Infinity\`, or a number which is integer, positive, safe, and > 0!`);
}
this.#timeout = options.timeout;
}
this.#userAgent = options.userAgent ?? userAgentDefault;
}
async #loadCacheStorage(): Promise<void> {
if (typeof this.#cacheStorageDefer !== "undefined") {
this.#cacheStorage = await this.#cacheStorageDefer;
this.#cacheStorageDefer = undefined;
}
}
/**
* Add HTTP status code that retryable.
* @param {...number} values Values.
* @returns {this}
*/
addHTTPStatusCodeRetryable(...values: number[]): this {
for (const value of values) {
this.#httpStatusCodesRetryable.add(value);
}
return this;
}
/**
* Delete HTTP status code that not retryable.
* @param {...number} values Values.
* @returns {this}
*/
deleteHTTPStatusCodeRetryable(...values: number[]): this {
for (const value of values) {
this.#httpStatusCodesRetryable.delete(value);
}
return this;
}
/**
* Fetch a resource from the network with extend features.
*
* > **🛡️ Permissions**
* >
* > | **Target** | **Type** | **Coverage** |
* > |:--|:--|:--|
* > | Deno | Network (`allow-net`) | Resource |
* @param {string | URL} input URL of the resource.
* @param {RequestInit} [init] Custom setting that apply to the request.
* @returns {Promise<Response>} Response.
*/
async fetch(input: string | URL, init?: RequestInit): Promise<Response> {
if (new URL(input).protocol === "file:") {
return fetch(input, init);
}
const requestCacheOption: RequestCache | undefined = init?.cache;
const requestCacheControl: boolean = new URL(input).protocol === "https:" && requestCacheOption !== "no-store" && (
typeof init === "undefined" ||
typeof init.method === "undefined" ||
init.method.toUpperCase() === "GET"
);
const requestFuzzy: Request = new Request(input, {
...init,
cache: undefined,
credentials: undefined,
keepalive: undefined,
method: init?.method?.toUpperCase(),
mode: undefined,
redirect: undefined,
signal: undefined,
window: undefined
});
let responseCached: Response | undefined = undefined;
if (requestCacheControl && requestCacheOption !== "reload") {
await this.#loadCacheStorage();
responseCached = await this.#cacheStorage?.match(requestFuzzy).catch();
}
if (requestCacheOption === "force-cache" && typeof responseCached !== "undefined") {
return responseCached;
}
const responseCachedETag: string | undefined = responseCached?.headers.get("ETag") ?? undefined;
const responseCachedLastModified: string | undefined = responseCached?.headers.get("Last-Modified") ?? undefined;
let responseCachedIsValid = false;
const requestHeaders: Headers = new Headers(init?.headers);
if (!requestHeaders.has("If-Match") && !requestHeaders.has("If-None-Match") && !requestHeaders.has("If-Range") && typeof responseCachedETag !== "undefined") {
responseCachedIsValid = true;
requestHeaders.set("If-None-Match", responseCachedETag);
}
if (!requestHeaders.has("If-Modified-Since") && !requestHeaders.has("If-Unmodified-Since") && !requestHeaders.has("If-Range") && typeof responseCachedLastModified !== "undefined") {
responseCachedIsValid = true;
requestHeaders.set("If-Modified-Since", responseCachedLastModified!);
}
if (!requestHeaders.has("User-Agent") && this.#userAgent.length > 0) {
requestHeaders.set("User-Agent", this.#userAgent);
}
const requestRedirectControl: boolean = this.#redirect.maximum !== Infinity && (
typeof init === "undefined" ||
typeof init.redirect === "undefined" ||
init.redirect === "follow"
);
const requestSignal: AbortSignal | undefined = init?.signal ?? ((this.#timeout === Infinity) ? undefined : AbortSignal.timeout(this.#timeout));
let requestFetchInput: string | URL = input;
const requestFetchInit: RequestInit = {
...init,
headers: requestHeaders,
redirect: requestRedirectControl ? "manual" : init?.redirect,
signal: requestSignal
};
let redirects = 0;
let retries = 0;
let response: Response;
do {
response = await fetch(requestFetchInput, requestFetchInit);
if (response.status === 304) {
if (typeof responseCached !== "undefined" && responseCachedIsValid) {
return responseCached;
}
break;
}
if (requestRedirectControl && httpStatusCodesRedirectable.has(response.status)) {
if (redirects >= this.#redirect.maximum) {
break;
}
const redirectURL: string | null = response.headers.get("Location");
if (redirectURL === null) {
break;
}
redirects += 1;
try {
requestFetchInput = new URL(redirectURL, input);
} catch {
break;
}
const delayTime: number = resolveDelayTime(this.#redirect.delay);
if (typeof this.#redirect.onEvent !== "undefined") {
void this.#redirect.onEvent({
countCurrent: redirects,
countMaximum: this.#redirect.maximum,
redirectAfter: delayTime,
redirectURL: new URL(requestFetchInput),
statusCode: response.status,
statusText: response.statusText
});
}
await setDelay(delayTime, requestSignal);
continue;
}
if (
response.ok ||
retries >= this.#retry.maximum ||
!this.#httpStatusCodesRetryable.has(response.status)
) {
break;
}
retries += 1;
let delayTime: number;
try {
delayTime = new HTTPHeaderRetryAfter(response).getRemainTimeMilliseconds();
} catch {
delayTime = resolveDelayTime(this.#retry.delay);
}
if (typeof this.#retry.onEvent !== "undefined") {
void this.#retry.onEvent({
countCurrent: retries,
countMaximum: this.#retry.maximum,
retryAfter: delayTime,
retryURL: new URL(requestFetchInput),
statusCode: response.status,
statusText: response.statusText
});
}
await setDelay(delayTime, requestSignal);
} while (retries <= this.#retry.maximum);
if (requestCacheControl && response.ok && (
response.headers.has("ETag") ||
response.headers.has("Last-Modified")
)) {
await this.#loadCacheStorage();
this.#cacheStorage?.put(requestFuzzy, response).catch();
}
return response;
}
/**
* Fetch paginate resources from the network.
*
* > **⚠️ Important**
* >
* > Support URL paginate only.
*
* > **🛡️ Permissions**
* >
* > | **Target** | **Type** | **Coverage** |
* > |:--|:--|:--|
* > | Deno | Network (`allow-net`) | Resource |
* @param {string | URL} input URL of the first page of the resources.
* @param {RequestInit} init Custom setting that apply to each request.
* @param {ExFetchPaginateOptions} [optionsOverride={}] Options.
* @returns {Promise<Response[]>} Responses.
*/
async fetchPaginate(input: string | URL, init?: RequestInit, optionsOverride: ExFetchPaginateOptions = {}): Promise<Response[]> {
const options: ExFetchPaginateOptionsInternal = this.#resolvePaginateOptions("optionsOverride", optionsOverride);
const responses: Response[] = [];
for (let page = 1, uri: URL | null | undefined = new URL(input); page <= options.maximum && typeof uri !== "undefined" && uri !== null; page += 1) {
if (page > 1) {
const delayTime: number = resolveDelayTime(options.delay);
if (typeof options.onEvent !== "undefined") {
void options.onEvent({
countCurrent: page,
countMaximum: options.maximum,
paginateAfter: delayTime,
paginateURL: new URL(uri)
});
}
await setDelay(delayTime, init?.signal ?? undefined);
}
const uriLookUp: URL = uri;
uri = undefined;
const response: Response = await this.fetch(uriLookUp, init);
responses.push(response);
if (response.ok) {
let responseHeaderLink: HTTPHeaderLink;
try {
responseHeaderLink = HTTPHeaderLink.parse(response);
} catch (error) {
if (options.throwOnInvalidHeaderLink) {
throw new SyntaxError(`[${uriLookUp.toString()}] ${(error as Error)?.message ?? error}`);
}
}
if (typeof responseHeaderLink! !== "undefined") {
uri = options.linkUpNextPage({
currentHeaderLink: responseHeaderLink,
currentURL: uriLookUp
});
}
}
}
return responses;
}
}
export default ExFetch;
/**
* Fetch a resource from the network.
*
* > **🛡️ Permissions**
* >
* > | **Target** | **Type** | **Coverage** |
* > |:--|:--|:--|
* > | Deno | Network (`allow-net`) | Resource |
* @param {string | URL} input URL of the resource.
* @param {RequestInit} init Custom setting that apply to the request.
* @param {ExFetchOptions} [options={}] Options.
* @returns {Promise<Response>} Response.
*/
export function exFetch(input: string | URL, init?: RequestInit, options: ExFetchOptions = {}): Promise<Response> {
return new ExFetch(options).fetch(input, init);
}
/**
* Fetch paginate resources from the network.
*
* > **⚠️ Important**
* >
* > Support URL paginate only.
*
* > **🛡️ Permissions**
* >
* > | **Target** | **Type** | **Coverage** |
* > |:--|:--|:--|
* > | Deno | Network (`allow-net`) | Resource |
* @param {string | URL} input URL of the first page of the resources.
* @param {RequestInit} init Custom setting that apply to each request.
* @param {ExFetchOptions} [options={}] Options.
* @returns {Promise<Response[]>} Responses.
*/
export function exFetchPaginate(input: string | URL, init?: RequestInit, options: ExFetchOptions = {}): Promise<Response[]> {
return new ExFetch(options).fetchPaginate(input, init);
}