@superutils/fetch 1.2.1 → 1.2.3
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.
- package/README.md +232 -68
- package/dist/index.d.ts +351 -292
- package/dist/index.js +222 -153
- package/package.json +5 -5
package/dist/index.d.ts
CHANGED
|
@@ -1,12 +1,30 @@
|
|
|
1
1
|
import * as _superutils_promise from '@superutils/promise';
|
|
2
|
-
import { RetryOptions,
|
|
2
|
+
import { RetryOptions, RetryIfFunc, DeferredAsyncOptions, IPromisE } from '@superutils/promise';
|
|
3
3
|
export { DeferredAsyncOptions, ResolveError, ResolveIgnored } from '@superutils/promise';
|
|
4
4
|
import { ValueOrPromise } from '@superutils/core';
|
|
5
5
|
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
6
|
+
/** Commonly used content types for easier access */
|
|
7
|
+
declare const ContentType: {
|
|
8
|
+
readonly APPLICATION_JAVASCRIPT: "application/javascript";
|
|
9
|
+
readonly APPLICATION_JSON: "application/json";
|
|
10
|
+
readonly APPLICATION_OCTET_STREAM: "application/octet-stream";
|
|
11
|
+
readonly APPLICATION_PDF: "application/pdf";
|
|
12
|
+
readonly APPLICATION_X_WWW_FORM_URLENCODED: "application/x-www-form-urlencoded";
|
|
13
|
+
readonly APPLICATION_XML: "application/xml";
|
|
14
|
+
readonly APPLICATION_ZIP: "application/zip";
|
|
15
|
+
readonly AUDIO_MPEG: "audio/mpeg";
|
|
16
|
+
readonly MULTIPART_FORM_DATA: "multipart/form-data";
|
|
17
|
+
readonly TEXT_CSS: "text/css";
|
|
18
|
+
readonly TEXT_HTML: "text/html";
|
|
19
|
+
readonly TEXT_PLAIN: "text/plain";
|
|
20
|
+
readonly VIDEO_MP4: "video/mp4";
|
|
21
|
+
};
|
|
22
|
+
type ExcludeOptions<Target, // options to exclude
|
|
23
|
+
Options extends FetchOptions = FetchOptions> = Target extends FetchOptions ? {
|
|
24
|
+
headers?: Options['headers'];
|
|
25
|
+
} & Omit<Options, 'headers' | keyof Target> & Partial<Record<Exclude<keyof Target, 'headers'>, never>> : Options;
|
|
26
|
+
type ExcludePostOptions<Target> = ExcludeOptions<Target, PostOptions>;
|
|
27
|
+
type FetchArgs = [url: string | URL, options?: FetchOptions];
|
|
10
28
|
type FetchArgsInterceptor = [
|
|
11
29
|
url: string | URL,
|
|
12
30
|
options: FetchOptionsInterceptor
|
|
@@ -20,6 +38,10 @@ declare enum FetchAs {
|
|
|
20
38
|
response = "response",
|
|
21
39
|
text = "text"
|
|
22
40
|
}
|
|
41
|
+
/** Extract `FetchAs` from `FetchOptions` */
|
|
42
|
+
type FetchAsFromOptions<TOptions, TFallback = FetchAs.json> = TOptions extends {
|
|
43
|
+
as: infer As;
|
|
44
|
+
} ? As extends FetchAs ? As : TFallback : TFallback;
|
|
23
45
|
/** Custom fetch options (not used by built-in `fetch()`*/
|
|
24
46
|
type FetchCustomOptions = {
|
|
25
47
|
/**
|
|
@@ -28,10 +50,12 @@ type FetchCustomOptions = {
|
|
|
28
50
|
*/
|
|
29
51
|
as?: FetchAs;
|
|
30
52
|
abortCtrl?: AbortController;
|
|
53
|
+
body?: PostBody | (() => PostBody);
|
|
31
54
|
errMsgs?: FetchErrMsgs;
|
|
32
55
|
interceptors?: FetchInterceptors;
|
|
33
56
|
/** Request timeout in milliseconds. */
|
|
34
57
|
timeout?: number;
|
|
58
|
+
validateUrl?: boolean;
|
|
35
59
|
} & FetchRetryOptions;
|
|
36
60
|
/** Default args */
|
|
37
61
|
type FetchDeferredArgs<OmitMethod extends boolean = false> = [
|
|
@@ -214,7 +238,7 @@ type FetchInterceptorResult<Args extends unknown[] = FetchArgsInterceptor> = Int
|
|
|
214
238
|
* ---
|
|
215
239
|
* 1. Any exception thrown by interceptors will gracefully ignored.
|
|
216
240
|
* 2. Interceptors will be executed in the sequence they're given.
|
|
217
|
-
* 3. Execution priority: global
|
|
241
|
+
* 3. Execution priority: global interceptors will always be executed before local interceptors.
|
|
218
242
|
*
|
|
219
243
|
*
|
|
220
244
|
*
|
|
@@ -236,8 +260,8 @@ type FetchInterceptors = {
|
|
|
236
260
|
/**
|
|
237
261
|
* Fetch request options
|
|
238
262
|
*/
|
|
239
|
-
type FetchOptions = RequestInit & FetchCustomOptions;
|
|
240
|
-
type FetchOptionsDefaults = Omit<FetchOptionsInterceptor, 'as' | 'method'
|
|
263
|
+
type FetchOptions = Omit<RequestInit, 'body'> & FetchCustomOptions;
|
|
264
|
+
type FetchOptionsDefaults = Omit<FetchOptionsInterceptor, 'as' | 'method'>;
|
|
241
265
|
/**
|
|
242
266
|
* Fetch options available to interceptors
|
|
243
267
|
*/
|
|
@@ -271,7 +295,7 @@ type FetchRetryOptions = Omit<Partial<RetryOptions>, 'retry' | 'retryIf'> & {
|
|
|
271
295
|
* Default: `0`
|
|
272
296
|
*/
|
|
273
297
|
retry?: number;
|
|
274
|
-
retryIf?:
|
|
298
|
+
retryIf?: RetryIfFunc<Response>;
|
|
275
299
|
};
|
|
276
300
|
/**
|
|
277
301
|
* Generic fetch interceptor type
|
|
@@ -284,64 +308,194 @@ type PostArgs<OmitMethod = false> = [
|
|
|
284
308
|
options?: OmitMethod extends true ? Omit<FetchOptions, 'method'> : PostOptions
|
|
285
309
|
];
|
|
286
310
|
/**
|
|
287
|
-
* Dynamic arguments for
|
|
311
|
+
* Dynamic arguments for deferred post-like methods.
|
|
288
312
|
*
|
|
289
313
|
* @example
|
|
290
314
|
* ```typescript
|
|
315
|
+
* import fetch, { type PostDeferredCbArgs } from '@superutils/fetch'
|
|
316
|
+
*
|
|
291
317
|
* // test with types
|
|
292
|
-
* type T1 =
|
|
293
|
-
* type T2 =
|
|
294
|
-
* type T3 =
|
|
295
|
-
* type T4 =
|
|
318
|
+
* type T1 = PostDeferredCbArgs<string | URL, undefined> // expected: [data, options]
|
|
319
|
+
* type T2 = PostDeferredCbArgs<undefined, string> // expected: [url, options]
|
|
320
|
+
* type T3 = PostDeferredCbArgs // expected: [url, data, options]
|
|
321
|
+
* type T4 = PostDeferredCbArgs<string, string> // expected: [options]
|
|
296
322
|
*
|
|
297
323
|
* const data = { name: 'test' }
|
|
298
324
|
* const url = 'https://domain.com'
|
|
299
|
-
* // test with
|
|
300
|
-
* const f1 =
|
|
325
|
+
* // test with fetch.post.deferred()
|
|
326
|
+
* const f1 = fetch.post.deferred({}, 'https://domain.com')
|
|
301
327
|
* // expected: [data, options]
|
|
302
328
|
* f1({data: 1}).then(console.log, console.warn)
|
|
303
329
|
*
|
|
304
|
-
* const f2 =
|
|
330
|
+
* const f2 = fetch.post.deferred({}, undefined, 'dome data')
|
|
305
331
|
* // expected: [url, options]
|
|
306
332
|
* f2('https').then(console.log, console.warn)
|
|
307
333
|
*
|
|
308
|
-
* const f3 =
|
|
334
|
+
* const f3 = fetch.post.deferred({})
|
|
309
335
|
* // expected: [url, data, options]
|
|
310
336
|
* f3('https://domain.com').then(console.log, console.warn)
|
|
311
337
|
*
|
|
312
|
-
* const f4 =
|
|
338
|
+
* const f4 = fetch.post.deferred({}, 'url', 'data')
|
|
313
339
|
* // expected: [options]
|
|
314
340
|
* f4().then(console.log, console.warn)
|
|
315
341
|
* ```
|
|
316
342
|
*/
|
|
317
|
-
type PostDeferredCbArgs<TUrl = undefined, TData = undefined,
|
|
318
|
-
|
|
343
|
+
type PostDeferredCbArgs<TUrl = undefined, TData = undefined, Options = undefined, CbArgsReq extends unknown[] = Required<PostArgs>> = [TUrl, TData] extends [CbArgsReq[0], undefined] ? [
|
|
344
|
+
data?: PostArgs[1],
|
|
345
|
+
options?: PostArgs[2]
|
|
346
|
+
] : [
|
|
347
|
+
TUrl,
|
|
348
|
+
TData
|
|
349
|
+
] extends [undefined, CbArgsReq[1]] ? [url: PostArgs[0], options?: PostArgs[2]] : [
|
|
350
|
+
TUrl,
|
|
351
|
+
TData
|
|
352
|
+
] extends [CbArgsReq[0], CbArgsReq[1]] ? [options?: PostArgs[2]] : [TUrl, TData, Options];
|
|
353
|
+
/** Request options for POST-like methods that allow "options.body" */
|
|
354
|
+
type PostOptions = {
|
|
319
355
|
/** Default: `'post'` */
|
|
320
356
|
method?: 'post' | 'put' | 'patch' | 'delete' | 'POST' | 'PUT' | 'PATCH' | 'DELETE';
|
|
321
|
-
}
|
|
357
|
+
} & Omit<FetchOptions, 'method'>;
|
|
322
358
|
|
|
323
|
-
/**
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
359
|
+
/**
|
|
360
|
+
* Create a reusable fetch client with shared options. The returned function comes attached with a
|
|
361
|
+
* `.deferred()` function for debounce and throttle behavior.
|
|
362
|
+
*
|
|
363
|
+
* The `createClient` utility streamlines the creation of dedicated API clients by generating pre-configured fetch
|
|
364
|
+
* functions. These functions can be equipped with default options like headers, timeouts, or a specific HTTP method,
|
|
365
|
+
* which minimizes code repetition across your application. If a method is not specified during creation, the client
|
|
366
|
+
* will default to `GET`.
|
|
367
|
+
*
|
|
368
|
+
* The returned client also includes a `.deferred()` method, providing the same debounce, throttle, and sequential
|
|
369
|
+
* execution capabilities found in functions like `fetch.get.deferred()`.
|
|
370
|
+
*
|
|
371
|
+
* @example create reusable clients
|
|
372
|
+
* ```javascript
|
|
373
|
+
* import { createClient } from '@superutils/fetch'
|
|
374
|
+
*
|
|
375
|
+
* // Create a "GET" client with default headers and a 5-second timeout
|
|
376
|
+
* const apiClient = createClient(
|
|
377
|
+
* {
|
|
378
|
+
* // fixed options cannot be overridden
|
|
379
|
+
* method: 'get',
|
|
380
|
+
* },
|
|
381
|
+
* {
|
|
382
|
+
* // default options can be overridden
|
|
383
|
+
* headers: {
|
|
384
|
+
* Authorization: 'Bearer my-secret-token',
|
|
385
|
+
* 'Content-Type': 'application/json',
|
|
386
|
+
* },
|
|
387
|
+
* timeout: 5000,
|
|
388
|
+
* },
|
|
389
|
+
* {
|
|
390
|
+
* // default defer options (can be overridden)
|
|
391
|
+
* delayMs: 300,
|
|
392
|
+
* retry: 2, // If request fails, retry up to two more times
|
|
393
|
+
* },
|
|
394
|
+
* )
|
|
395
|
+
*
|
|
396
|
+
* // Use it just like the standard fetch
|
|
397
|
+
* apiClient('https://dummyjson.com/products/1', {
|
|
398
|
+
* // The 'method' property cannot be overridden as it is used in the fixed options when creating the client.
|
|
399
|
+
* // In TypeScript, the compiler will not allow this property.
|
|
400
|
+
* // In Javascript, it will simply be ignored.
|
|
401
|
+
* // method: 'post',
|
|
402
|
+
* timeout: 3000, // The 'timeout' property can be overridden
|
|
403
|
+
* }).then(console.log, console.warn)
|
|
404
|
+
*
|
|
405
|
+
* // create a deferred client using "apiClient"
|
|
406
|
+
* const deferredClient = apiClient.deferred(
|
|
407
|
+
* { retry: 0 }, // disable retrying by overriding the `retry` defer option
|
|
408
|
+
* 'https://dummyjson.com/products/1',
|
|
409
|
+
* { timeout: 3000 },
|
|
410
|
+
* )
|
|
411
|
+
* deferredClient({ timeout: 10000 }) // timeout is overridden by individual request
|
|
412
|
+
* .then(console.log, console.warn)
|
|
413
|
+
* ```
|
|
414
|
+
*/
|
|
415
|
+
declare const createClient: <FixedOpts extends FetchOptions | undefined, CommonOpts extends ExcludeOptions<FixedOpts> | undefined, FixedAs extends FetchAs | undefined = FetchAsFromOptions<FixedOpts, undefined>>(
|
|
416
|
+
/** Mandatory fetch options that cannot be overriden by individual request */
|
|
417
|
+
fixedOptions?: FixedOpts,
|
|
418
|
+
/** Common fetch options that can be overriden by individual request */
|
|
419
|
+
commonOptions?: FetchOptions & CommonOpts, commonDeferOptions?: DeferredAsyncOptions<unknown, unknown>) => {
|
|
420
|
+
<T, TOptions extends ExcludeOptions<FixedOpts> | undefined = ExcludeOptions<FixedOpts> | undefined, TAs extends FetchAs = FixedAs extends FetchAs ? FixedAs : FetchAsFromOptions<TOptions, FetchAsFromOptions<CommonOpts>>, TReturn = FetchResult<T>[TAs]>(url: FetchArgs[0], options?: TOptions): IPromisE<TReturn>;
|
|
421
|
+
deferred<ThisArg = unknown, Delay extends number = number, DefaultUrl extends FetchArgs[0] | undefined = string | URL | undefined, DefaultOptions extends ExcludeOptions<FixedOpts> | undefined = ExcludeOptions<FixedOpts> | undefined>(deferOptions?: DeferredAsyncOptions<ThisArg, Delay>, defaultUrl?: DefaultUrl, defaultOptions?: DefaultOptions): <TResult = unknown, TOptions_1 extends ExcludeOptions<FixedOpts> | undefined = ExcludeOptions<FixedOpts> | undefined, TAs_1 extends FetchAs = FixedAs extends FetchAs ? FixedAs : FetchAsFromOptions<TOptions_1, FetchAsFromOptions<CommonOpts>>, TReturn_1 = FetchResult<TResult>[TAs_1]>(...args: DefaultUrl extends undefined ? [url: FetchArgs[0], options?: TOptions_1] : [options?: TOptions_1]) => IPromisE<TReturn_1>;
|
|
327
422
|
};
|
|
328
423
|
|
|
329
424
|
/**
|
|
330
|
-
* Create a
|
|
331
|
-
*
|
|
425
|
+
* Create a reusable fetch client with shared options. The returned function comes attached with a
|
|
426
|
+
* `.deferred()` function for debounced and throttled request.
|
|
427
|
+
* While `createClient()` is versatile enough for any HTTP method, `createPostClient()` is specifically designed for
|
|
428
|
+
* methods that require a request body, such as `DELETE`, `PATCH`, `POST`, and `PUT`. If a method is not provided, it
|
|
429
|
+
* defaults to `POST`. The generated client accepts an additional second parameter (`data`) for the request payload.
|
|
430
|
+
*
|
|
431
|
+
* Similar to `createClient`, the returned function comes equipped with a `.deferred()` method, enabling debounced,
|
|
432
|
+
* throttled, or sequential execution.
|
|
433
|
+
*
|
|
434
|
+
* @example create reusable clients
|
|
435
|
+
* ```javascript
|
|
436
|
+
* import { createPostClient, FetchAs } from '@superutils/fetch'
|
|
437
|
+
*
|
|
438
|
+
* // Create a POST client with 10-second as the default timeout
|
|
439
|
+
* const postClient = createPostClient(
|
|
440
|
+
* {
|
|
441
|
+
* method: 'post',
|
|
442
|
+
* headers: { 'content-type': 'application/json' },
|
|
443
|
+
* },
|
|
444
|
+
* { timeout: 10000 },
|
|
445
|
+
* )
|
|
446
|
+
*
|
|
447
|
+
* // Invoking `postClient()` automatically applies the pre-configured options
|
|
448
|
+
* postClient(
|
|
449
|
+
* 'https://dummyjson.com/products/add',
|
|
450
|
+
* { title: 'New Product' }, // data/body
|
|
451
|
+
* {}, // other options
|
|
452
|
+
* ).then(console.log)
|
|
453
|
+
*
|
|
454
|
+
* // create a deferred client using "postClient"
|
|
455
|
+
* const updateProduct = postClient.deferred(
|
|
456
|
+
* {
|
|
457
|
+
* delayMs: 300, // debounce duration
|
|
458
|
+
* },
|
|
459
|
+
* 'https://dummyjson.com/products/1',
|
|
460
|
+
* {
|
|
461
|
+
* method: 'patch',
|
|
462
|
+
* timeout: 3000,
|
|
463
|
+
* },
|
|
464
|
+
* )
|
|
465
|
+
* updateProduct({ title: 'New title 1' }) // ignored by debounce
|
|
466
|
+
* updateProduct({ title: 'New title 2' }) // executed
|
|
467
|
+
* ```
|
|
332
468
|
*/
|
|
333
|
-
declare const
|
|
334
|
-
|
|
335
|
-
|
|
469
|
+
declare const createPostClient: <FixedOpts extends PostOptions | undefined, CommonOpts extends ExcludePostOptions<FixedOpts> | undefined, FixedAs extends FetchAs | undefined = FetchAsFromOptions<FixedOpts, undefined>>(
|
|
470
|
+
/** Mandatory fetch options that cannot be overriden by individual request */
|
|
471
|
+
fixedOptions?: FixedOpts,
|
|
472
|
+
/** Common fetch options that can be overriden by individual request */
|
|
473
|
+
commonOptions?: PostOptions & CommonOpts, commonDeferOptions?: DeferredAsyncOptions<unknown, unknown>) => {
|
|
474
|
+
<T = unknown, TOptions extends ExcludePostOptions<FixedOpts> | undefined = ExcludePostOptions<FixedOpts> | undefined, TAs extends FetchAs = FixedAs extends FetchAs ? FixedAs : FetchAsFromOptions<TOptions, FetchAsFromOptions<CommonOpts>>, TReturn = FetchResult<T>[TAs]>(url: PostArgs[0], data?: PostArgs[1], options?: TOptions): IPromisE<TReturn>;
|
|
475
|
+
deferred<ThisArg, Delay extends number, DefaultUrl extends PostArgs[0] | undefined, DefaultData extends PostArgs[1] = undefined, DefaultOptions extends ExcludePostOptions<FixedOpts> | undefined = undefined>(deferOptions?: DeferredAsyncOptions<ThisArg, Delay>, defaultUrl?: DefaultUrl, defaultData?: DefaultData, defaultOptions?: DefaultOptions): <TResult = unknown, TOptions_1 extends ExcludePostOptions<FixedOpts> | undefined = ExcludePostOptions<FixedOpts>, TAs_1 extends FetchAs = FixedAs extends FetchAs ? FixedAs : FetchAsFromOptions<TOptions_1, FetchAsFromOptions<CommonOpts>>, TReturn_1 = FetchResult<TResult>[TAs_1]>(...args: PostDeferredCbArgs<DefaultUrl, DefaultData, TOptions_1>) => IPromisE<TReturn_1>;
|
|
336
476
|
};
|
|
337
477
|
|
|
478
|
+
/**
|
|
479
|
+
* Gracefully executes interceptors and returns the processed value.
|
|
480
|
+
* If the value is not transformed (by returning a new value) by the interceptors,
|
|
481
|
+
* the original value is returned.
|
|
482
|
+
*
|
|
483
|
+
* @param value value to be passed to the interceptors
|
|
484
|
+
* @param interceptors interceptor callbacks
|
|
485
|
+
* @param args (optional) common arguments to be supplied to all the interceptors in addition to
|
|
486
|
+
* the `value' which will always be the first argument.
|
|
487
|
+
*
|
|
488
|
+
* Interceptor arguments: `[value, ...args]`
|
|
489
|
+
*/
|
|
490
|
+
declare const executeInterceptors: <T, TArgs extends unknown[]>(value: T, interceptors?: Interceptor<T, TArgs>[], ...args: TArgs) => Promise<T>;
|
|
491
|
+
|
|
338
492
|
/**
|
|
339
493
|
* Extended `fetch` with timeout, retry, and other options. Automatically parses as JSON by default on success.
|
|
340
494
|
*
|
|
341
495
|
* @param url request URL
|
|
342
496
|
* @param options (optional) Standard `fetch` options extended with {@link FetchCustomOptions}.
|
|
343
|
-
* Default content
|
|
344
|
-
* @param options.as (optional) determines
|
|
497
|
+
* Default "content-type" header is 'application/json'.
|
|
498
|
+
* @param options.as (optional) determines how to parse the result. Default: {@link FetchAs.json}
|
|
345
499
|
* @param options.method (optional) fetch method. Default: `'get'`
|
|
346
500
|
*
|
|
347
501
|
* @example Make a simple HTTP requests
|
|
@@ -354,7 +508,7 @@ declare const createPostMethodFunc: (method?: Pick<PostOptions, "method">["metho
|
|
|
354
508
|
* ```
|
|
355
509
|
*/
|
|
356
510
|
declare const fetch: {
|
|
357
|
-
<T, TOptions extends FetchOptions = FetchOptions, TAs extends FetchAs = TOptions["as"] extends FetchAs ? TOptions["as"] : FetchAs.json, TReturn = FetchResult<T>[TAs]>(url: string | URL, options?: TOptions): IPromisE<TReturn>;
|
|
511
|
+
<T, TOptions extends FetchOptions = FetchOptions, TAs extends FetchAs = TOptions["as"] extends FetchAs ? TOptions["as"] : FetchAs.json, TReturn = FetchResult<T>[TAs]>(url: string | URL, options?: FetchOptions & TOptions): IPromisE<TReturn>;
|
|
358
512
|
/** Default fetch options */
|
|
359
513
|
defaults: FetchOptionsDefaults;
|
|
360
514
|
};
|
|
@@ -363,12 +517,10 @@ declare const fetch: {
|
|
|
363
517
|
* Drop-in replacement for built-in `fetch()` with with timeout, retry etc options and Response as default return type.
|
|
364
518
|
*
|
|
365
519
|
* @param url request URL
|
|
366
|
-
* @param options (optional) Standard `fetch` options extended with
|
|
367
|
-
* @param options.as (optional) determines who to parse the result. Default: {@link FetchAs.response}
|
|
368
|
-
* @param options.method (optional) fetch method. Default: `'get'`
|
|
520
|
+
* @param options (optional) Standard `fetch` options extended with "FetchCustomOptions"
|
|
369
521
|
*
|
|
370
522
|
* @example Make a simple HTTP requests
|
|
371
|
-
* ```
|
|
523
|
+
* ```javascript
|
|
372
524
|
* import { fetchResponse } from '@superutils/fetch'
|
|
373
525
|
*
|
|
374
526
|
* fetchResponse('https://dummyjson.com/products/1')
|
|
@@ -376,53 +528,120 @@ declare const fetch: {
|
|
|
376
528
|
* .then(console.log, console.error)
|
|
377
529
|
* ```
|
|
378
530
|
*/
|
|
379
|
-
declare const fetchResponse: <T = Response, TOptions extends FetchOptions = FetchOptions, TAs extends FetchAs = TOptions["as"] extends FetchAs ? TOptions["as"] : FetchAs.response, TReturn = FetchResult<T>[TAs]>(
|
|
531
|
+
declare const fetchResponse: <T = Response, TOptions extends FetchOptions = FetchOptions, TAs extends FetchAs = TOptions["as"] extends FetchAs ? TOptions["as"] : FetchAs.response, TReturn = FetchResult<T>[TAs]>(url: FetchArgs[0], options: Parameters<typeof fetch<T, TOptions, TAs, TReturn>>[1]) => IPromisE<TReturn>;
|
|
380
532
|
|
|
381
|
-
declare const
|
|
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
|
-
/** Make HTTP
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
|
|
533
|
+
declare const methods: {
|
|
534
|
+
/** Make HTTP requests with method GET */
|
|
535
|
+
get: {
|
|
536
|
+
<T, TOptions extends ({
|
|
537
|
+
headers?: HeadersInit | undefined;
|
|
538
|
+
} & Omit<FetchOptions, "headers" | "method"> & Partial<Record<"method", never>>) | undefined = ({
|
|
539
|
+
headers?: HeadersInit | undefined;
|
|
540
|
+
} & Omit<FetchOptions, "headers" | "method"> & Partial<Record<"method", never>>) | undefined, TAs extends FetchAs = FetchAsFromOptions<TOptions, FetchAs.json>, TReturn = FetchResult<T>[TAs]>(url: FetchArgs[0], options?: TOptions | undefined): _superutils_promise.IPromisE<TReturn>;
|
|
541
|
+
deferred<ThisArg = unknown, Delay extends number = number, DefaultUrl extends FetchArgs[0] | undefined = string | URL | undefined, DefaultOptions extends ({
|
|
542
|
+
headers?: HeadersInit | undefined;
|
|
543
|
+
} & Omit<FetchOptions, "headers" | "method"> & Partial<Record<"method", never>>) | undefined = ({
|
|
544
|
+
headers?: HeadersInit | undefined;
|
|
545
|
+
} & Omit<FetchOptions, "headers" | "method"> & Partial<Record<"method", never>>) | undefined>(deferOptions?: _superutils_promise.DeferredAsyncOptions<ThisArg, Delay>, defaultUrl?: DefaultUrl | undefined, defaultOptions?: DefaultOptions | undefined): <TResult = unknown, TOptions extends ({
|
|
546
|
+
headers?: HeadersInit | undefined;
|
|
547
|
+
} & Omit<FetchOptions, "headers" | "method"> & Partial<Record<"method", never>>) | undefined = ({
|
|
548
|
+
headers?: HeadersInit | undefined;
|
|
549
|
+
} & Omit<FetchOptions, "headers" | "method"> & Partial<Record<"method", never>>) | undefined, TAs extends FetchAs = FetchAsFromOptions<TOptions, FetchAs.json>, TReturn = FetchResult<TResult>[TAs]>(...args: DefaultUrl extends undefined ? [url: string | URL, options?: TOptions | undefined] : [options?: TOptions | undefined]) => _superutils_promise.IPromisE<TReturn>;
|
|
550
|
+
};
|
|
551
|
+
/** Make HTTP requests with method HEAD */
|
|
552
|
+
head: {
|
|
553
|
+
<T, TOptions extends ({
|
|
554
|
+
headers?: HeadersInit | undefined;
|
|
555
|
+
} & Omit<FetchOptions, "headers" | "method"> & Partial<Record<"method", never>>) | undefined = ({
|
|
556
|
+
headers?: HeadersInit | undefined;
|
|
557
|
+
} & Omit<FetchOptions, "headers" | "method"> & Partial<Record<"method", never>>) | undefined, TAs extends FetchAs = FetchAsFromOptions<TOptions, FetchAs.json>, TReturn = FetchResult<T>[TAs]>(url: FetchArgs[0], options?: TOptions | undefined): _superutils_promise.IPromisE<TReturn>;
|
|
558
|
+
deferred<ThisArg = unknown, Delay extends number = number, DefaultUrl extends FetchArgs[0] | undefined = string | URL | undefined, DefaultOptions extends ({
|
|
559
|
+
headers?: HeadersInit | undefined;
|
|
560
|
+
} & Omit<FetchOptions, "headers" | "method"> & Partial<Record<"method", never>>) | undefined = ({
|
|
561
|
+
headers?: HeadersInit | undefined;
|
|
562
|
+
} & Omit<FetchOptions, "headers" | "method"> & Partial<Record<"method", never>>) | undefined>(deferOptions?: _superutils_promise.DeferredAsyncOptions<ThisArg, Delay>, defaultUrl?: DefaultUrl | undefined, defaultOptions?: DefaultOptions | undefined): <TResult = unknown, TOptions extends ({
|
|
563
|
+
headers?: HeadersInit | undefined;
|
|
564
|
+
} & Omit<FetchOptions, "headers" | "method"> & Partial<Record<"method", never>>) | undefined = ({
|
|
565
|
+
headers?: HeadersInit | undefined;
|
|
566
|
+
} & Omit<FetchOptions, "headers" | "method"> & Partial<Record<"method", never>>) | undefined, TAs extends FetchAs = FetchAsFromOptions<TOptions, FetchAs.json>, TReturn = FetchResult<TResult>[TAs]>(...args: DefaultUrl extends undefined ? [url: string | URL, options?: TOptions | undefined] : [options?: TOptions | undefined]) => _superutils_promise.IPromisE<TReturn>;
|
|
567
|
+
};
|
|
568
|
+
/** Make HTTP requests with method OPTIONS */
|
|
569
|
+
options: {
|
|
570
|
+
<T, TOptions extends ({
|
|
571
|
+
headers?: HeadersInit | undefined;
|
|
572
|
+
} & Omit<FetchOptions, "headers" | "method"> & Partial<Record<"method", never>>) | undefined = ({
|
|
573
|
+
headers?: HeadersInit | undefined;
|
|
574
|
+
} & Omit<FetchOptions, "headers" | "method"> & Partial<Record<"method", never>>) | undefined, TAs extends FetchAs = FetchAsFromOptions<TOptions, FetchAs.json>, TReturn = FetchResult<T>[TAs]>(url: FetchArgs[0], options?: TOptions | undefined): _superutils_promise.IPromisE<TReturn>;
|
|
575
|
+
deferred<ThisArg = unknown, Delay extends number = number, DefaultUrl extends FetchArgs[0] | undefined = string | URL | undefined, DefaultOptions extends ({
|
|
576
|
+
headers?: HeadersInit | undefined;
|
|
577
|
+
} & Omit<FetchOptions, "headers" | "method"> & Partial<Record<"method", never>>) | undefined = ({
|
|
578
|
+
headers?: HeadersInit | undefined;
|
|
579
|
+
} & Omit<FetchOptions, "headers" | "method"> & Partial<Record<"method", never>>) | undefined>(deferOptions?: _superutils_promise.DeferredAsyncOptions<ThisArg, Delay>, defaultUrl?: DefaultUrl | undefined, defaultOptions?: DefaultOptions | undefined): <TResult = unknown, TOptions extends ({
|
|
580
|
+
headers?: HeadersInit | undefined;
|
|
581
|
+
} & Omit<FetchOptions, "headers" | "method"> & Partial<Record<"method", never>>) | undefined = ({
|
|
582
|
+
headers?: HeadersInit | undefined;
|
|
583
|
+
} & Omit<FetchOptions, "headers" | "method"> & Partial<Record<"method", never>>) | undefined, TAs extends FetchAs = FetchAsFromOptions<TOptions, FetchAs.json>, TReturn = FetchResult<TResult>[TAs]>(...args: DefaultUrl extends undefined ? [url: string | URL, options?: TOptions | undefined] : [options?: TOptions | undefined]) => _superutils_promise.IPromisE<TReturn>;
|
|
584
|
+
};
|
|
585
|
+
/** Make HTTP requests with method DELETE */
|
|
586
|
+
delete: {
|
|
587
|
+
<T = unknown, TOptions extends ({
|
|
588
|
+
headers?: HeadersInit | undefined;
|
|
589
|
+
} & Omit<PostOptions, "headers" | "method"> & Partial<Record<"method", never>>) | undefined = ({
|
|
590
|
+
headers?: HeadersInit | undefined;
|
|
591
|
+
} & Omit<PostOptions, "headers" | "method"> & Partial<Record<"method", never>>) | undefined, TAs extends FetchAs = FetchAsFromOptions<TOptions, FetchAs.json>, TReturn = FetchResult<T>[TAs]>(url: PostArgs[0], data?: PostArgs[1], options?: TOptions | undefined): _superutils_promise.IPromisE<TReturn>;
|
|
592
|
+
deferred<ThisArg, Delay extends number, DefaultUrl extends PostArgs[0] | undefined, DefaultData extends PostArgs[1] = undefined, DefaultOptions extends ({
|
|
593
|
+
headers?: HeadersInit | undefined;
|
|
594
|
+
} & Omit<PostOptions, "headers" | "method"> & Partial<Record<"method", never>>) | undefined = undefined>(deferOptions?: _superutils_promise.DeferredAsyncOptions<ThisArg, Delay>, defaultUrl?: DefaultUrl | undefined, defaultData?: DefaultData | undefined, defaultOptions?: DefaultOptions | undefined): <TResult = unknown, TOptions extends ({
|
|
595
|
+
headers?: HeadersInit | undefined;
|
|
596
|
+
} & Omit<PostOptions, "headers" | "method"> & Partial<Record<"method", never>>) | undefined = {
|
|
597
|
+
headers?: HeadersInit | undefined;
|
|
598
|
+
} & Omit<PostOptions, "headers" | "method"> & Partial<Record<"method", never>>, TAs extends FetchAs = FetchAsFromOptions<TOptions, FetchAs.json>, TReturn = FetchResult<TResult>[TAs]>(...args: PostDeferredCbArgs<DefaultUrl, DefaultData, TOptions, [url: string | URL, data: PostBody | (() => PostBody), options: PostOptions]>) => _superutils_promise.IPromisE<TReturn>;
|
|
599
|
+
};
|
|
600
|
+
/** Make HTTP requests with method PATCH */
|
|
601
|
+
patch: {
|
|
602
|
+
<T = unknown, TOptions extends ({
|
|
603
|
+
headers?: HeadersInit | undefined;
|
|
604
|
+
} & Omit<PostOptions, "headers" | "method"> & Partial<Record<"method", never>>) | undefined = ({
|
|
605
|
+
headers?: HeadersInit | undefined;
|
|
606
|
+
} & Omit<PostOptions, "headers" | "method"> & Partial<Record<"method", never>>) | undefined, TAs extends FetchAs = FetchAsFromOptions<TOptions, FetchAs.json>, TReturn = FetchResult<T>[TAs]>(url: PostArgs[0], data?: PostArgs[1], options?: TOptions | undefined): _superutils_promise.IPromisE<TReturn>;
|
|
607
|
+
deferred<ThisArg, Delay extends number, DefaultUrl extends PostArgs[0] | undefined, DefaultData extends PostArgs[1] = undefined, DefaultOptions extends ({
|
|
608
|
+
headers?: HeadersInit | undefined;
|
|
609
|
+
} & Omit<PostOptions, "headers" | "method"> & Partial<Record<"method", never>>) | undefined = undefined>(deferOptions?: _superutils_promise.DeferredAsyncOptions<ThisArg, Delay>, defaultUrl?: DefaultUrl | undefined, defaultData?: DefaultData | undefined, defaultOptions?: DefaultOptions | undefined): <TResult = unknown, TOptions extends ({
|
|
610
|
+
headers?: HeadersInit | undefined;
|
|
611
|
+
} & Omit<PostOptions, "headers" | "method"> & Partial<Record<"method", never>>) | undefined = {
|
|
612
|
+
headers?: HeadersInit | undefined;
|
|
613
|
+
} & Omit<PostOptions, "headers" | "method"> & Partial<Record<"method", never>>, TAs extends FetchAs = FetchAsFromOptions<TOptions, FetchAs.json>, TReturn = FetchResult<TResult>[TAs]>(...args: PostDeferredCbArgs<DefaultUrl, DefaultData, TOptions, [url: string | URL, data: PostBody | (() => PostBody), options: PostOptions]>) => _superutils_promise.IPromisE<TReturn>;
|
|
614
|
+
};
|
|
615
|
+
/** Make HTTP requests with method POST */
|
|
616
|
+
post: {
|
|
617
|
+
<T = unknown, TOptions extends ({
|
|
618
|
+
headers?: HeadersInit | undefined;
|
|
619
|
+
} & Omit<PostOptions, "headers" | "method"> & Partial<Record<"method", never>>) | undefined = ({
|
|
620
|
+
headers?: HeadersInit | undefined;
|
|
621
|
+
} & Omit<PostOptions, "headers" | "method"> & Partial<Record<"method", never>>) | undefined, TAs extends FetchAs = FetchAsFromOptions<TOptions, FetchAs.json>, TReturn = FetchResult<T>[TAs]>(url: PostArgs[0], data?: PostArgs[1], options?: TOptions | undefined): _superutils_promise.IPromisE<TReturn>;
|
|
622
|
+
deferred<ThisArg, Delay extends number, DefaultUrl extends PostArgs[0] | undefined, DefaultData extends PostArgs[1] = undefined, DefaultOptions extends ({
|
|
623
|
+
headers?: HeadersInit | undefined;
|
|
624
|
+
} & Omit<PostOptions, "headers" | "method"> & Partial<Record<"method", never>>) | undefined = undefined>(deferOptions?: _superutils_promise.DeferredAsyncOptions<ThisArg, Delay>, defaultUrl?: DefaultUrl | undefined, defaultData?: DefaultData | undefined, defaultOptions?: DefaultOptions | undefined): <TResult = unknown, TOptions extends ({
|
|
625
|
+
headers?: HeadersInit | undefined;
|
|
626
|
+
} & Omit<PostOptions, "headers" | "method"> & Partial<Record<"method", never>>) | undefined = {
|
|
627
|
+
headers?: HeadersInit | undefined;
|
|
628
|
+
} & Omit<PostOptions, "headers" | "method"> & Partial<Record<"method", never>>, TAs extends FetchAs = FetchAsFromOptions<TOptions, FetchAs.json>, TReturn = FetchResult<TResult>[TAs]>(...args: PostDeferredCbArgs<DefaultUrl, DefaultData, TOptions, [url: string | URL, data: PostBody | (() => PostBody), options: PostOptions]>) => _superutils_promise.IPromisE<TReturn>;
|
|
629
|
+
};
|
|
630
|
+
/** Make HTTP requests with method PUT */
|
|
631
|
+
put: {
|
|
632
|
+
<T = unknown, TOptions extends ({
|
|
633
|
+
headers?: HeadersInit | undefined;
|
|
634
|
+
} & Omit<PostOptions, "headers" | "method"> & Partial<Record<"method", never>>) | undefined = ({
|
|
635
|
+
headers?: HeadersInit | undefined;
|
|
636
|
+
} & Omit<PostOptions, "headers" | "method"> & Partial<Record<"method", never>>) | undefined, TAs extends FetchAs = FetchAsFromOptions<TOptions, FetchAs.json>, TReturn = FetchResult<T>[TAs]>(url: PostArgs[0], data?: PostArgs[1], options?: TOptions | undefined): _superutils_promise.IPromisE<TReturn>;
|
|
637
|
+
deferred<ThisArg, Delay extends number, DefaultUrl extends PostArgs[0] | undefined, DefaultData extends PostArgs[1] = undefined, DefaultOptions extends ({
|
|
638
|
+
headers?: HeadersInit | undefined;
|
|
639
|
+
} & Omit<PostOptions, "headers" | "method"> & Partial<Record<"method", never>>) | undefined = undefined>(deferOptions?: _superutils_promise.DeferredAsyncOptions<ThisArg, Delay>, defaultUrl?: DefaultUrl | undefined, defaultData?: DefaultData | undefined, defaultOptions?: DefaultOptions | undefined): <TResult = unknown, TOptions extends ({
|
|
640
|
+
headers?: HeadersInit | undefined;
|
|
641
|
+
} & Omit<PostOptions, "headers" | "method"> & Partial<Record<"method", never>>) | undefined = {
|
|
642
|
+
headers?: HeadersInit | undefined;
|
|
643
|
+
} & Omit<PostOptions, "headers" | "method"> & Partial<Record<"method", never>>, TAs extends FetchAs = FetchAsFromOptions<TOptions, FetchAs.json>, TReturn = FetchResult<TResult>[TAs]>(...args: PostDeferredCbArgs<DefaultUrl, DefaultData, TOptions, [url: string | URL, data: PostBody | (() => PostBody), options: PostOptions]>) => _superutils_promise.IPromisE<TReturn>;
|
|
644
|
+
};
|
|
426
645
|
};
|
|
427
646
|
/**
|
|
428
647
|
* A `fetch()` replacement that simplifies data fetching with automatic JSON parsing, request timeouts, retries,
|
|
@@ -465,49 +684,21 @@ type FetchWithMethods = typeof fetchResponse & {
|
|
|
465
684
|
* - FetchAs.json: `unknown`
|
|
466
685
|
* - FetchAs.text: `string`
|
|
467
686
|
* - FetchAs.response: `Response`
|
|
687
|
+
*
|
|
468
688
|
* @param url
|
|
469
689
|
* @param options (optional) Standard `fetch` options extended with {@link FetchCustomOptions}
|
|
470
|
-
* @param options.
|
|
690
|
+
* @param options.abortCtrl (optional) if not provided `AbortController` will be instantiated when `timeout` used.
|
|
691
|
+
* @param options.as (optional) (optional) specify how to parse the result. Default: {@link FetchAs.json}
|
|
692
|
+
* For raw `Response` use {@link FetchAs.response}
|
|
471
693
|
* @param options.headers (optional) request headers
|
|
472
|
-
* Default: `{ 'content-type':
|
|
694
|
+
* Default: `{ 'content-type': 'application/json' }` (or whaterver is set in the `fetch.defaults`).
|
|
695
|
+
* @param options.interceptors (optional) request interceptor callbacks. See {@link FetchInterceptors} for details.
|
|
473
696
|
* @param options.method (optional) fetch method. Default: `'get'`
|
|
697
|
+
* @param options.timeout (optional) duration in milliseconds to abort the request if it takes longer.
|
|
474
698
|
*
|
|
475
|
-
* Options' default values (excluding `as`, `method` and `retryIf`) can be configured to be EFFECTIVE GLOBALLY.
|
|
476
|
-
*
|
|
477
|
-
* ```typescript
|
|
478
|
-
* import fetch from '@superutils/fetch'
|
|
479
|
-
*
|
|
480
|
-
* fetch.defaults = {
|
|
481
|
-
* errMsgs: {
|
|
482
|
-
* invalidUrl: 'Invalid URL',
|
|
483
|
-
* parseFailed: 'Failed to parse response as',
|
|
484
|
-
* reqTimedout: 'Request timed out',
|
|
485
|
-
* requestFailed: 'Request failed with status code:',
|
|
486
|
-
* },
|
|
487
|
-
* headers: new Headers([['content-type', 'application/json']]),
|
|
488
|
-
* // Global/application-wide Interceptor & Transfermers
|
|
489
|
-
* interceptors: {
|
|
490
|
-
* error: [],
|
|
491
|
-
* request: [],
|
|
492
|
-
* response: [],
|
|
493
|
-
* result: [],
|
|
494
|
-
* },
|
|
495
|
-
* timeout: 0,
|
|
496
|
-
* //........
|
|
497
|
-
* }
|
|
498
|
-
* ```
|
|
499
|
-
*
|
|
500
|
-
* @property options.abortCtrl (optional) if not provided `AbortController` will be instantiated when `timeout` used.
|
|
501
|
-
* @property options.headers (optional) request headers. Default: `{ 'content-type' : 'application/json'}`
|
|
502
|
-
* @property options.interceptors (optional) request interceptor callbacks. See {@link FetchInterceptors} for details.
|
|
503
|
-
* @property options.method (optional) Default: `"get"`
|
|
504
|
-
* @property options.timeout (optional) duration in milliseconds to abort the request if it takes longer.
|
|
505
|
-
* @property options.parse (optional) specify how to parse the result.
|
|
506
|
-
* Default: {@link FetchAs.json}
|
|
507
|
-
* For raw `Response` use {@link FetchAs.response}
|
|
508
699
|
*
|
|
509
|
-
* @example Drop-in replacement for built-in
|
|
510
|
-
* ```
|
|
700
|
+
* @example Drop-in replacement for built-in fetch
|
|
701
|
+
* ```javascript
|
|
511
702
|
* import fetch from '@superutils/fetch'
|
|
512
703
|
*
|
|
513
704
|
* fetch('https://dummyjson.com/products/1')
|
|
@@ -516,7 +707,7 @@ type FetchWithMethods = typeof fetchResponse & {
|
|
|
516
707
|
* ```
|
|
517
708
|
*
|
|
518
709
|
* @example Method specific function with JSON parsing by default
|
|
519
|
-
* ```
|
|
710
|
+
* ```javascript
|
|
520
711
|
* import fetch from '@superutils/fetch'
|
|
521
712
|
*
|
|
522
713
|
* // no need for `response.json()` or `result.data.data` drilling
|
|
@@ -529,195 +720,60 @@ type FetchWithMethods = typeof fetchResponse & {
|
|
|
529
720
|
* fetch.post('https://dummyjson.com/products/add', { title: 'Product title' })
|
|
530
721
|
* .then(product => console.log(product))
|
|
531
722
|
* ```
|
|
532
|
-
*/
|
|
533
|
-
declare const fetchDefault: FetchWithMethods;
|
|
534
|
-
|
|
535
|
-
/**
|
|
536
|
-
* Creates a deferred/throttled version of {@link fetch}, powered by {@link PromisE.deferred}.
|
|
537
|
-
* This is ideal for scenarios requiring advanced control over HTTP requests, such as debouncing search inputs,
|
|
538
|
-
* throttling API calls, or ensuring sequential request execution.
|
|
539
723
|
*
|
|
540
|
-
* It leverages the robust capabilities of the underlying {@link fetch} function, which includes features like request timeouts and manual abortion.
|
|
541
|
-
* `fetchDeferred` uses this to automatically abort pending requests when a new one is initiated, preventing race conditions and redundant network traffic.
|
|
542
724
|
*
|
|
543
|
-
* @
|
|
544
|
-
* See {@link DeferredAsyncOptions} for details.
|
|
545
|
-
* @param defaultUrl (optional) If a global URL is `undefined`, returned callback will always require an URL.
|
|
546
|
-
* @param defaultOptions (optional) Default {@link FetchOptions} to be used by the returned function.
|
|
547
|
-
* Default options will be merged with the options provided in the callback.
|
|
548
|
-
* If the same property is provided in both cases, defaults will be overriden by the callback.
|
|
725
|
+
* @example Set default options.
|
|
549
726
|
*
|
|
550
|
-
*
|
|
551
|
-
* ```typescript
|
|
552
|
-
* import { fetchDeferred, ResolveIgnored } from '@superutils/fetch'
|
|
553
|
-
*
|
|
554
|
-
* // Create a debounced search function with a 300ms delay.
|
|
555
|
-
* const searchProducts = fetchDeferred({
|
|
556
|
-
* delayMs: 300, // Debounce delay
|
|
557
|
-
* resolveIgnored: ResolveIgnored.WITH_UNDEFINED, // Ignored (aborted) promises will resolve with `undefined`
|
|
558
|
-
* })
|
|
559
|
-
*
|
|
560
|
-
* // User types 'iphone'
|
|
561
|
-
* searchProducts('https://dummyjson.com/products/search?q=iphone').then(result => {
|
|
562
|
-
* console.log('Result for "iphone":', result);
|
|
563
|
-
* });
|
|
564
|
-
*
|
|
565
|
-
* // Before 300ms has passed, the user continues typing 'iphone 9'
|
|
566
|
-
* setTimeout(() => {
|
|
567
|
-
* searchProducts('https://dummyjson.com/products/search?q=iphone 9').then(result => {
|
|
568
|
-
* console.log('Result for "iphone 9":', result);
|
|
569
|
-
* });
|
|
570
|
-
* }, 200);
|
|
571
|
-
*
|
|
572
|
-
* // Outcome:
|
|
573
|
-
* // The first request for "iphone" is aborted.
|
|
574
|
-
* // The first promise resolves with `undefined`.
|
|
575
|
-
* // The second request for "iphone 9" is executed after the 300ms debounce delay.
|
|
576
|
-
* ```
|
|
727
|
+
* Options' default values (excluding `as` and `method`) can be configured to be EFFECTIVE GLOBALLY.
|
|
577
728
|
*
|
|
578
|
-
* @example Creating a reusable, pre-configured client
|
|
579
729
|
* ```typescript
|
|
580
|
-
* import
|
|
581
|
-
*
|
|
582
|
-
* // Create a throttled function to fetch a random quote.
|
|
583
|
-
* // The URL and a 3-second timeout are set as defaults, creating a reusable client.
|
|
584
|
-
* const getRandomQuote = fetchDeferred(
|
|
585
|
-
* {
|
|
586
|
-
* delayMs: 300, // Throttle window
|
|
587
|
-
* throttle: true,
|
|
588
|
-
* // Ignored calls will resolve with the result of the last successful call.
|
|
589
|
-
* resolveIgnored: ResolveIgnored.WITH_LAST,
|
|
590
|
-
* },
|
|
591
|
-
* 'https://dummyjson.com/quotes/random', // Default URL
|
|
592
|
-
* { timeout: 3000 }, // Default fetch options
|
|
593
|
-
* )
|
|
594
|
-
*
|
|
595
|
-
* // Call the function multiple times in quick succession.
|
|
596
|
-
* getRandomQuote().then(quote => console.log('Call 1 resolved:', quote.id));
|
|
597
|
-
* getRandomQuote().then(quote => console.log('Call 2 resolved:', quote.id));
|
|
598
|
-
* getRandomQuote().then(quote => console.log('Call 3 resolved:', quote.id));
|
|
730
|
+
* import fetch from '@superutils/fetch'
|
|
599
731
|
*
|
|
600
|
-
*
|
|
601
|
-
*
|
|
602
|
-
*
|
|
603
|
-
*
|
|
604
|
-
*
|
|
732
|
+
* fetch.defaults = {
|
|
733
|
+
* errMsgs: {
|
|
734
|
+
* invalidUrl: 'Invalid URL',
|
|
735
|
+
* parseFailed: 'Failed to parse response as',
|
|
736
|
+
* reqTimedout: 'Request timed out',
|
|
737
|
+
* requestFailed: 'Request failed with status code:',
|
|
738
|
+
* },
|
|
739
|
+
* headers: new Headers([['content-type', 'application/json']]),
|
|
740
|
+
* // Global/application-wide Interceptor & Transfermers
|
|
741
|
+
* interceptors: {
|
|
742
|
+
* error: [],
|
|
743
|
+
* request: [],
|
|
744
|
+
* response: [],
|
|
745
|
+
* result: [],
|
|
746
|
+
* },
|
|
747
|
+
* timeout: 0,
|
|
748
|
+
* //........
|
|
749
|
+
* }
|
|
605
750
|
* ```
|
|
606
751
|
*/
|
|
607
|
-
declare
|
|
752
|
+
declare const fetchDefault: typeof fetchResponse & typeof methods;
|
|
608
753
|
|
|
609
754
|
/**
|
|
610
|
-
*
|
|
611
|
-
* {@link PromisE.deferred}.
|
|
612
|
-
*
|
|
613
|
-
* This is ideal for scenarios like auto-saving form data, preventing duplicate submissions on button clicks,
|
|
614
|
-
* or throttling API updates.
|
|
615
|
-
*
|
|
616
|
-
* Like `fetchDeferred`, it automatically aborts pending requests when a new one is initiated, ensuring only
|
|
617
|
-
* the most recent or relevant action is executed.
|
|
755
|
+
* Add AbortController to options if not present and propagate external abort signal if provided.
|
|
618
756
|
*
|
|
619
|
-
* @param
|
|
620
|
-
* See {@link DeferredAsyncOptions} for details.
|
|
621
|
-
* @param defaultUrl (optional) If default URL is `undefined`, returned callback will always require an URL.
|
|
622
|
-
* @param defaultData (optional) If default data is `undefined`, returned callback will allow a data parameter.
|
|
623
|
-
* @param defaultOptions (optional) Default {@link FetchOptions} to be used by the returned function.
|
|
624
|
-
* Default options will be merged with the options provided in the callback.
|
|
625
|
-
* If the same property is provided in both cases, defaults will be overriden by the callback.
|
|
757
|
+
* @param options The fetch options object.
|
|
626
758
|
*
|
|
759
|
+
* @returns The AbortController instance associated with the options.
|
|
760
|
+
*/
|
|
761
|
+
declare const getAbortCtrl: (options: Partial<FetchOptions>) => AbortController;
|
|
762
|
+
|
|
763
|
+
/**
|
|
764
|
+
* Execute built-in `fetch()` and retry if request fails and `options.retry > 0`.
|
|
627
765
|
*
|
|
628
|
-
*
|
|
629
|
-
*
|
|
630
|
-
* ```typescript
|
|
631
|
-
* import fetch from '@superutils/fetch'
|
|
632
|
-
* import PromisE from '@superutils/promise'
|
|
633
|
-
*
|
|
634
|
-
* // Create a throttled function to auto-save product updates.
|
|
635
|
-
* const saveProductThrottled = fetch.post.deferred(
|
|
636
|
-
* {
|
|
637
|
-
* delayMs: 1000, // Throttle window of 1 second
|
|
638
|
-
* throttle: true,
|
|
639
|
-
* trailing: true, // Ensures the very last update is always saved
|
|
640
|
-
* onResult: product => console.log(`[Saved] Product: ${product.title}`),
|
|
641
|
-
* },
|
|
642
|
-
* 'https://dummyjson.com/products/add', // Default URL
|
|
643
|
-
* )
|
|
644
|
-
* // Simulate a user typing quickly, triggering multiple saves.
|
|
645
|
-
* console.log('User starts typing...')
|
|
646
|
-
*
|
|
647
|
-
* // Executed immediately (leading edge)
|
|
648
|
-
* saveProductThrottled({ title: 'iPhone' })
|
|
649
|
-
* // Ignored (within 1000ms throttle window)
|
|
650
|
-
* PromisE.delay(200, () => saveProductThrottled({ title: 'iPhone 15' }))
|
|
651
|
-
* // Ignored
|
|
652
|
-
* PromisE.delay(300, () => saveProductThrottled({ title: 'iPhone 15 Pro' }))
|
|
653
|
-
* // Queued to execute on the trailing edge
|
|
654
|
-
* PromisE.delay(400, () => saveProductThrottled({ title: 'iPhone 15 Pro Max' }))
|
|
655
|
-
* // Outcome:
|
|
656
|
-
* // The first call ('iPhone') is executed immediately.
|
|
657
|
-
* // The next two calls are ignored by the throttle.
|
|
658
|
-
* // The final call ('iPhone 15 Pro Max') is executed after the 1000ms throttle window closes,
|
|
659
|
-
* // thanks to `trailing: true`.
|
|
660
|
-
* // This results in only two network requests instead of four.
|
|
661
|
-
* ```
|
|
662
|
-
*
|
|
663
|
-
* #### Example 2: debouncing an authentication token refresh
|
|
664
|
-
*
|
|
665
|
-
* ```typescript
|
|
666
|
-
* import fetch from '@superutils/fetch'
|
|
667
|
-
* import PromisE from '@superutils/promise'
|
|
668
|
-
*
|
|
669
|
-
* // Mock a simple token store
|
|
670
|
-
* let currentRefreshToken = ''
|
|
671
|
-
* // Create a debounced function to refresh the auth token.
|
|
672
|
-
* // It waits 300ms after the last call before executing.
|
|
673
|
-
* const requestNewToken = fetch.post.deferred(
|
|
674
|
-
* {
|
|
675
|
-
* delayMs: 300, // debounce delay
|
|
676
|
-
* onResult: ({ refreshToken = '' }) => {
|
|
677
|
-
* console.log(
|
|
678
|
-
* `Auth token successfully refreshed at ${new Date().toISOString()}`,
|
|
679
|
-
* )
|
|
680
|
-
* currentRefreshToken = refreshToken
|
|
681
|
-
* },
|
|
682
|
-
* },
|
|
683
|
-
* 'https://dummyjson.com/auth/refresh', // Default URL
|
|
684
|
-
* () => ({
|
|
685
|
-
* refreshToken: currentRefreshToken,
|
|
686
|
-
* expiresInMins: 30,
|
|
687
|
-
* }),
|
|
688
|
-
* )
|
|
766
|
+
* @param url request URL
|
|
767
|
+
* @param options (optional)
|
|
689
768
|
*
|
|
690
|
-
*
|
|
691
|
-
* fetch
|
|
692
|
-
* .post<{ refreshToken: string }>(
|
|
693
|
-
* 'https://dummyjson.com/auth/login',
|
|
694
|
-
* {
|
|
695
|
-
* username: 'emilys',
|
|
696
|
-
* password: 'emilyspass',
|
|
697
|
-
* expiresInMins: 30,
|
|
698
|
-
* },
|
|
699
|
-
* { credentials: 'include' },
|
|
700
|
-
* )
|
|
701
|
-
* .then(result => {
|
|
702
|
-
* currentRefreshToken = result?.refreshToken
|
|
703
|
-
*
|
|
704
|
-
* requestNewToken() // Called at 0ms
|
|
705
|
-
* PromisE.delay(50, requestNewToken) // Called at 50ms
|
|
706
|
-
* PromisE.delay(100, requestNewToken) // Called at 100ms
|
|
707
|
-
* }, console.error)
|
|
708
|
-
* // Outcome:
|
|
709
|
-
* // The first two calls are aborted by the debounce mechanism.
|
|
710
|
-
* // Only the final call executes, 300ms after it was made (at the 400ms mark).
|
|
711
|
-
* // The token is refreshed only once, preventing redundant network requests.
|
|
712
|
-
* ```
|
|
769
|
+
* @returns response
|
|
713
770
|
*/
|
|
714
|
-
declare
|
|
771
|
+
declare const getResponse: (url: FetchArgs[0], options?: FetchArgs[1]) => Promise<Response>;
|
|
715
772
|
|
|
716
773
|
/**
|
|
717
774
|
* Merge one or more {@link FetchOptions}
|
|
718
775
|
*
|
|
719
776
|
* Notes:
|
|
720
|
-
* - {@link config.fetchOptions} will be added as the base and not necessary to be included
|
|
721
777
|
* - item properties will be prioritized in the order of sequence they were passed in
|
|
722
778
|
* - the following properties will be merged
|
|
723
779
|
* * `errMsgs`
|
|
@@ -729,4 +785,7 @@ declare function postDeferred<ThisArg, Delay = unknown, DefaultUrl extends PostA
|
|
|
729
785
|
*/
|
|
730
786
|
declare const mergeFetchOptions: (...allOptions: FetchOptions[]) => FetchOptionsInterceptor;
|
|
731
787
|
|
|
732
|
-
|
|
788
|
+
/** Merges partial fetch options ignoring empty or undefined. Otherwise, will return the first argument. */
|
|
789
|
+
declare const mergePartialOptions: (...optionsAr: (Partial<FetchOptions> | undefined)[]) => Partial<FetchOptions> | undefined;
|
|
790
|
+
|
|
791
|
+
export { ContentType, type ExcludeOptions, type ExcludePostOptions, type FetchArgs, type FetchArgsInterceptor, FetchAs, type FetchAsFromOptions, type FetchCustomOptions, type FetchDeferredArgs, type FetchErrMsgs, FetchError, type FetchInterceptorError, type FetchInterceptorRequest, type FetchInterceptorResponse, type FetchInterceptorResult, type FetchInterceptors, type FetchOptions, type FetchOptionsDefaults, type FetchOptionsInterceptor, type FetchResult, type FetchRetryOptions, type Interceptor, type PostArgs, type PostBody, type PostDeferredCbArgs, type PostOptions, createClient, createPostClient, fetchDefault as default, executeInterceptors, fetch, fetchResponse, getAbortCtrl, getResponse, mergeFetchOptions, mergePartialOptions };
|