@superutils/fetch 1.2.3 → 1.3.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.
- package/README.md +94 -97
- package/dist/index.d.ts +203 -127
- package/dist/index.js +156 -127
- package/package.json +5 -5
package/README.md
CHANGED
|
@@ -67,39 +67,39 @@ All fetch calls return a `PromisE` (`@superutils/promise`) instance which means
|
|
|
67
67
|
|
|
68
68
|
1. Status tracking: all instances come with `.pending`, `.resolved` and `.rejected` attributes that indicate the current state of the promise.
|
|
69
69
|
|
|
70
|
-
|
|
71
|
-
|
|
70
|
+
```javascript
|
|
71
|
+
import fetch from '@superutils/fetch'
|
|
72
72
|
|
|
73
|
-
|
|
73
|
+
const request = fetch('https://dummyjson.com/products/1')
|
|
74
74
|
|
|
75
|
-
|
|
75
|
+
console.log(request.pending) // true
|
|
76
76
|
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
77
|
+
request.then(() => {
|
|
78
|
+
console.log(request.resolved) // true
|
|
79
|
+
console.log(request.pending) // false
|
|
80
|
+
console.log(request.rejected) // false
|
|
81
|
+
})
|
|
82
|
+
```
|
|
83
83
|
|
|
84
84
|
2. Early finalization: all `PromisE` instances expose `.resolve()` and `.reject()` methods that allow early finalization and `.onEarlyFinalize` array that allows adding callbacks to be executed when the promise is finalized externally using these methods. Fetch promises utilize this to abort the request when appropriate.
|
|
85
85
|
|
|
86
|
-
|
|
87
|
-
|
|
86
|
+
```javascript
|
|
87
|
+
import fetch from '@superutils/fetch'
|
|
88
88
|
|
|
89
|
-
|
|
90
|
-
|
|
89
|
+
// Request that will take 5 seconds to resolve
|
|
90
|
+
const request = fetch('https://dummyjson.com/products?delay=5000')
|
|
91
91
|
|
|
92
|
-
|
|
92
|
+
request.then(result => console.log(result), console.warn)
|
|
93
93
|
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
94
|
+
// Add a callback to do stuff whenever request is aborted externally.
|
|
95
|
+
// This will not be invoked if fetch fails or resolves (promise finalized naturally) using the Promise executor.
|
|
96
|
+
request.onEarlyFinalize.push((resolved, valueOrReason) =>
|
|
97
|
+
console.log('Aborted externally:', { resolved, valueOrReason }),
|
|
98
|
+
)
|
|
99
99
|
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
100
|
+
// resolve/reject before the promise is finalized
|
|
101
|
+
request.reject(new Error('No longer needed'))
|
|
102
|
+
```
|
|
103
103
|
|
|
104
104
|
<div id="methods"></div>
|
|
105
105
|
|
|
@@ -362,86 +362,82 @@ The following interceptor callbacks allow intercepting and/or transforming at di
|
|
|
362
362
|
- Value returned (transformed) by an interceptor will be carried over to the subsequent interceptor of the same type.
|
|
363
363
|
- There are 2 category of interceptors:
|
|
364
364
|
- Local: interceptors provided when making a request.
|
|
365
|
+
- Global: interceptors that are executed application-wide on every request. Global interceptors can be added/accessed at `fetch.defaults.interceptors`. Global interceptors are always executed before local interceptors.
|
|
365
366
|
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
```javascript
|
|
369
|
-
import fetch, { FetchError } from '@superutils/fetch'
|
|
370
|
-
|
|
371
|
-
const interceptors = {
|
|
372
|
-
error: [
|
|
373
|
-
(err, url, options) => {
|
|
374
|
-
console.log('Request failed', err, url, options)
|
|
375
|
-
// return nothing/undefined to keep the error unchanged
|
|
376
|
-
// or return modified/new error
|
|
377
|
-
err.message = 'My custom error message!'
|
|
378
|
-
// or create a new FetchError by cloning it (make sure all the required properties are set correctly)
|
|
379
|
-
return err.clone('My custom error message!')
|
|
380
|
-
},
|
|
381
|
-
],
|
|
382
|
-
request: [
|
|
383
|
-
(url, options) => {
|
|
384
|
-
// add extra headers or modify request options here
|
|
385
|
-
options.headers.append('x-custom-header', 'some value')
|
|
386
|
-
|
|
387
|
-
// transform the URL by returning a modified URL
|
|
388
|
-
return url + '?param=value'
|
|
389
|
-
},
|
|
390
|
-
],
|
|
391
|
-
response: [
|
|
392
|
-
(response, url, options) => {
|
|
393
|
-
if (response.ok) return
|
|
394
|
-
console.log('request was successful', { url, options })
|
|
395
|
-
|
|
396
|
-
// You can transform the response by returning different `Response` object or even make a completely new HTTP reuqest.
|
|
397
|
-
// You can transform the response by returning different `Response` object or even make a completely new HTTP request.
|
|
398
|
-
// The subsequent response interceptors will receive the returned response
|
|
399
|
-
return fetch('https://dummyjson.com/products/1') // promise will be resolved automatically
|
|
400
|
-
},
|
|
401
|
-
],
|
|
402
|
-
result: [
|
|
403
|
-
(result, url, options) => {
|
|
404
|
-
const productId = Number(
|
|
405
|
-
new URL(url).pathname.split('/products/')[1],
|
|
406
|
-
)
|
|
407
|
-
if (options.method === 'get' && !Number.isNaN(productId)) {
|
|
408
|
-
result.title ??= 'Unknown title'
|
|
409
|
-
}
|
|
410
|
-
return result
|
|
411
|
-
},
|
|
412
|
-
],
|
|
413
|
-
}
|
|
414
|
-
fetch
|
|
415
|
-
.get('https://dummyjson.com/products/1', { interceptors })
|
|
416
|
-
.then(product => console.log({ product }))
|
|
417
|
-
```
|
|
367
|
+
**Example: Interceptor usage**
|
|
418
368
|
|
|
419
|
-
|
|
369
|
+
```javascript
|
|
370
|
+
import fetch, { FetchError } from '@superutils/fetch'
|
|
371
|
+
|
|
372
|
+
const interceptors = {
|
|
373
|
+
error: [
|
|
374
|
+
(err, url, options) => {
|
|
375
|
+
console.log('Request failed', err, url, options)
|
|
376
|
+
// return nothing/undefined to keep the error unchanged
|
|
377
|
+
// or return modified/new error
|
|
378
|
+
err.message = 'My custom error message!'
|
|
379
|
+
// or create a new FetchError by cloning it (make sure all the required properties are set correctly)
|
|
380
|
+
return err.clone('My custom error message!')
|
|
381
|
+
},
|
|
382
|
+
],
|
|
383
|
+
request: [
|
|
384
|
+
(url, options) => {
|
|
385
|
+
// add extra headers or modify request options here
|
|
386
|
+
options.headers.append('x-custom-header', 'some value')
|
|
387
|
+
|
|
388
|
+
// transform the URL by returning a modified URL
|
|
389
|
+
return url + '?param=value'
|
|
390
|
+
},
|
|
391
|
+
],
|
|
392
|
+
response: [
|
|
393
|
+
(response, url, options) => {
|
|
394
|
+
if (response.ok) return
|
|
395
|
+
console.log('request was successful', { url, options })
|
|
396
|
+
|
|
397
|
+
// You can transform the response by returning different `Response` object or even make a completely new HTTP reuqest.
|
|
398
|
+
// You can transform the response by returning different `Response` object or even make a completely new HTTP request.
|
|
399
|
+
// The subsequent response interceptors will receive the returned response
|
|
400
|
+
return fetch('https://dummyjson.com/products/1') // promise will be resolved automatically
|
|
401
|
+
},
|
|
402
|
+
],
|
|
403
|
+
result: [
|
|
404
|
+
(result, url, options) => {
|
|
405
|
+
const productId = Number(
|
|
406
|
+
new URL(url).pathname.split('/products/')[1],
|
|
407
|
+
)
|
|
408
|
+
if (options.method === 'get' && !Number.isNaN(productId)) {
|
|
409
|
+
result.title ??= 'Unknown title'
|
|
410
|
+
}
|
|
411
|
+
return result
|
|
412
|
+
},
|
|
413
|
+
],
|
|
414
|
+
}
|
|
415
|
+
fetch
|
|
416
|
+
.get('https://dummyjson.com/products/1', { interceptors })
|
|
417
|
+
.then(product => console.log({ product }))
|
|
418
|
+
```
|
|
420
419
|
|
|
421
|
-
|
|
420
|
+
**Example: Add global request and error interceptors**
|
|
422
421
|
|
|
423
|
-
|
|
424
|
-
|
|
422
|
+
```javascript
|
|
423
|
+
import fetch from '@superutils/fetch'
|
|
425
424
|
|
|
426
|
-
|
|
425
|
+
const { interceptors } = fetch.defaults
|
|
427
426
|
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
|
|
427
|
+
interceptors.request.push((url, options) => {
|
|
428
|
+
// a headers to all requests make by the application
|
|
429
|
+
// add headers to all requests made by the application
|
|
430
|
+
options.headers.append('x-auth', 'token')
|
|
431
|
+
})
|
|
433
432
|
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
|
|
433
|
+
interceptors.error.push((err, url, options) => {
|
|
434
|
+
// log whenever a request fails
|
|
435
|
+
console.log('Error interceptor', err)
|
|
436
|
+
})
|
|
438
437
|
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
|
|
442
|
-
console.warn,
|
|
443
|
-
)
|
|
444
|
-
```
|
|
438
|
+
// Each time a requst is made using @superutils/fetch, the above interceptors will be executed when appropriate
|
|
439
|
+
fetch('https://dummyjson.com/products/1').then(console.log, console.warn)
|
|
440
|
+
```
|
|
445
441
|
|
|
446
442
|
<div id="retry"></div>
|
|
447
443
|
|
|
@@ -569,7 +565,7 @@ While `createClient()` is versatile enough for any HTTP method, `createPostClien
|
|
|
569
565
|
Similar to `createClient`, the returned function comes equipped with a `.deferred()` method, enabling debounced, throttled, or sequential execution.
|
|
570
566
|
|
|
571
567
|
```javascript
|
|
572
|
-
import { createPostClient
|
|
568
|
+
import { createPostClient } from '@superutils/fetch'
|
|
573
569
|
|
|
574
570
|
// Create a POST client with 10-second as the default timeout
|
|
575
571
|
const postClient = createPostClient(
|
|
@@ -591,8 +587,9 @@ postClient(
|
|
|
591
587
|
const updateProduct = postClient.deferred(
|
|
592
588
|
{
|
|
593
589
|
delayMs: 300, // debounce duration
|
|
590
|
+
onResult: console.log, // prints only successful results
|
|
594
591
|
},
|
|
595
|
-
'https://dummyjson.com/products/
|
|
592
|
+
'https://dummyjson.com/products/add',
|
|
596
593
|
{
|
|
597
594
|
method: 'patch',
|
|
598
595
|
timeout: 3000,
|
package/dist/index.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import * as _superutils_promise from '@superutils/promise';
|
|
2
|
-
import { RetryOptions, RetryIfFunc, DeferredAsyncOptions,
|
|
2
|
+
import { RetryOptions, RetryIfFunc, DeferredAsyncOptions, IPromisE_Timeout } from '@superutils/promise';
|
|
3
3
|
export { DeferredAsyncOptions, ResolveError, ResolveIgnored } from '@superutils/promise';
|
|
4
4
|
import { ValueOrPromise } from '@superutils/core';
|
|
5
5
|
|
|
@@ -19,16 +19,6 @@ declare const ContentType: {
|
|
|
19
19
|
readonly TEXT_PLAIN: "text/plain";
|
|
20
20
|
readonly VIDEO_MP4: "video/mp4";
|
|
21
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];
|
|
28
|
-
type FetchArgsInterceptor = [
|
|
29
|
-
url: string | URL,
|
|
30
|
-
options: FetchOptionsInterceptor
|
|
31
|
-
];
|
|
32
22
|
declare enum FetchAs {
|
|
33
23
|
arrayBuffer = "arrayBuffer",
|
|
34
24
|
blob = "blob",
|
|
@@ -38,53 +28,18 @@ declare enum FetchAs {
|
|
|
38
28
|
response = "response",
|
|
39
29
|
text = "text"
|
|
40
30
|
}
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
type FetchCustomOptions = {
|
|
47
|
-
/**
|
|
48
|
-
* Specify how the parse the result. To get raw response use {@link FetchAs.response}.
|
|
49
|
-
* Default: 'json'
|
|
50
|
-
*/
|
|
51
|
-
as?: FetchAs;
|
|
52
|
-
abortCtrl?: AbortController;
|
|
53
|
-
body?: PostBody | (() => PostBody);
|
|
54
|
-
errMsgs?: FetchErrMsgs;
|
|
55
|
-
interceptors?: FetchInterceptors;
|
|
56
|
-
/** Request timeout in milliseconds. */
|
|
57
|
-
timeout?: number;
|
|
58
|
-
validateUrl?: boolean;
|
|
59
|
-
} & FetchRetryOptions;
|
|
60
|
-
/** Default args */
|
|
61
|
-
type FetchDeferredArgs<OmitMethod extends boolean = false> = [
|
|
62
|
-
url?: string | URL,
|
|
63
|
-
options?: Omit<FetchOptions, 'abortCtrl' | (OmitMethod extends true ? 'method' : never)>
|
|
64
|
-
];
|
|
65
|
-
type FetchErrMsgs = {
|
|
66
|
-
invalidUrl?: string;
|
|
67
|
-
parseFailed?: string;
|
|
68
|
-
reqTimedout?: string;
|
|
69
|
-
requestFailed?: string;
|
|
70
|
-
};
|
|
71
|
-
/** Custom error message for fetch requests with more detailed info about the request URL, fetch options and response */
|
|
72
|
-
declare class FetchError extends Error {
|
|
73
|
-
options: FetchOptions;
|
|
74
|
-
response?: Response;
|
|
75
|
-
url: string | URL;
|
|
76
|
-
constructor(message: string, options: {
|
|
77
|
-
cause?: unknown;
|
|
78
|
-
options: FetchOptions;
|
|
79
|
-
response?: Response;
|
|
80
|
-
url: string | URL;
|
|
81
|
-
});
|
|
82
|
-
clone: (newMessage: string) => FetchError;
|
|
83
|
-
}
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* Generic definition for interceptor and transformer callbacks used throughout the fetch lifecycle.
|
|
34
|
+
*/
|
|
35
|
+
type Interceptor<T, TArgs extends unknown[]> = (...args: [value: T, ...TArgs]) => ValueOrPromise<void> | ValueOrPromise<T>;
|
|
84
36
|
/**
|
|
85
37
|
* Fetch error interceptor to be invoked whenever an exception occurs.
|
|
86
38
|
* This interceptor can also be used as the error transformer by returning {@link FetchError}.
|
|
87
39
|
*
|
|
40
|
+
* Note: The error interceptor is only triggered if the request ultimately fails. If retries are enabled (`retry > 0`)
|
|
41
|
+
* and a subsequent attempt succeeds, this interceptor will not be invoked for the intermediate failures.
|
|
42
|
+
*
|
|
88
43
|
* @param {FetchError} fetchError custom error that also contain URL, options & response
|
|
89
44
|
*
|
|
90
45
|
* @returns returning undefined or not returning anything will not override the error
|
|
@@ -217,10 +172,10 @@ type FetchInterceptorResult<Args extends unknown[] = FetchArgsInterceptor> = Int
|
|
|
217
172
|
/**
|
|
218
173
|
* All valid interceptors for fetch requests are:
|
|
219
174
|
* ---
|
|
220
|
-
* 1. error
|
|
175
|
+
* 1. error
|
|
221
176
|
* 2. request
|
|
222
177
|
* 3. response
|
|
223
|
-
* 4. result
|
|
178
|
+
* 4. result
|
|
224
179
|
*
|
|
225
180
|
* An interceptor can be any of the following:
|
|
226
181
|
* ---
|
|
@@ -239,10 +194,9 @@ type FetchInterceptorResult<Args extends unknown[] = FetchArgsInterceptor> = Int
|
|
|
239
194
|
* 1. Any exception thrown by interceptors will gracefully ignored.
|
|
240
195
|
* 2. Interceptors will be executed in the sequence they're given.
|
|
241
196
|
* 3. Execution priority: global interceptors will always be executed before local interceptors.
|
|
197
|
+
* 4. The following options cannot be modified using interceptors: abortCtrl, as, signal, timeout
|
|
242
198
|
*
|
|
243
|
-
*
|
|
244
|
-
*
|
|
245
|
-
* More info & examples:
|
|
199
|
+
* More info about specific interceptor types & examples:
|
|
246
200
|
* ---
|
|
247
201
|
* See the following for more details and examples:
|
|
248
202
|
*
|
|
@@ -252,24 +206,108 @@ type FetchInterceptorResult<Args extends unknown[] = FetchArgsInterceptor> = Int
|
|
|
252
206
|
* - `result`: {@link FetchInterceptorResult}
|
|
253
207
|
*/
|
|
254
208
|
type FetchInterceptors = {
|
|
209
|
+
/** Request error interceptors/transformers. See {@link FetchInterceptorError} for more details. */
|
|
255
210
|
error?: FetchInterceptorError[];
|
|
211
|
+
/** Request request interceptors/transformers. See {@link FetchInterceptorRequest} for more details. */
|
|
256
212
|
request?: FetchInterceptorRequest[];
|
|
213
|
+
/** Request response interceptors/transformers. See {@link FetchInterceptorResponse} for more details. */
|
|
257
214
|
response?: FetchInterceptorResponse[];
|
|
215
|
+
/** Request result interceptors/transformers. See {@link FetchInterceptorResult} for more details. */
|
|
258
216
|
result?: FetchInterceptorResult[];
|
|
259
217
|
};
|
|
218
|
+
|
|
219
|
+
type ExcludeOptions<Target, // options to exclude
|
|
220
|
+
Options extends FetchOptions = FetchOptions> = Target extends FetchOptions ? {
|
|
221
|
+
headers?: Options['headers'];
|
|
222
|
+
} & Omit<Options, 'headers' | keyof Target> & Partial<Record<Exclude<keyof Target, 'headers'>, never>> : Options;
|
|
223
|
+
type ExcludePostOptions<Target> = ExcludeOptions<Target, PostOptions>;
|
|
224
|
+
type FetchArgs = [url: string | URL, options?: FetchOptions];
|
|
225
|
+
type FetchArgsInterceptor = [
|
|
226
|
+
url: string | URL,
|
|
227
|
+
options: FetchOptionsInterceptor
|
|
228
|
+
];
|
|
229
|
+
/** Extract `FetchAs` from `FetchOptions` */
|
|
230
|
+
type FetchAsFromOptions<TOptions, TFallback = FetchAs.json> = TOptions extends {
|
|
231
|
+
as: infer As;
|
|
232
|
+
} ? As extends FetchAs ? As : TFallback : TFallback;
|
|
233
|
+
/** Custom fetch options (not used by built-in `fetch()`*/
|
|
234
|
+
type FetchCustomOptions = {
|
|
235
|
+
/**
|
|
236
|
+
* Specify how the parse the result. To get raw response use {@link FetchAs.response}.
|
|
237
|
+
* Default: 'json'
|
|
238
|
+
*/
|
|
239
|
+
as?: FetchAs;
|
|
240
|
+
/**
|
|
241
|
+
* An `AbortController` instance to control the request.
|
|
242
|
+
*
|
|
243
|
+
* If not provided, a new instance is automatically created internally.
|
|
244
|
+
*
|
|
245
|
+
* It is supported in addition to the standard `signal`. If both are provided, `abortCtrl` will be aborted
|
|
246
|
+
* when the `signal` aborts or when the request times out.
|
|
247
|
+
*
|
|
248
|
+
* Recommendation:
|
|
249
|
+
* - For request timeout purposes, setting a timeout duration will be sufficient.
|
|
250
|
+
* Abort controller/signal is not needed.
|
|
251
|
+
* - Use `abortCtrl` instead of `signal` to prevent creating internal `AbortController` instance.
|
|
252
|
+
*/
|
|
253
|
+
abortCtrl?: AbortController;
|
|
254
|
+
body?: PostBody | (() => PostBody);
|
|
255
|
+
/**
|
|
256
|
+
* Custom fetch function to use instead of the global `fetch`.
|
|
257
|
+
* Useful for testing or using a different fetch implementation (e.g. `node-fetch` in older Node versions).
|
|
258
|
+
*
|
|
259
|
+
* Default: `globalThis.fetch`
|
|
260
|
+
*/
|
|
261
|
+
fetchFunc?: (...args: FetchArgs) => Promise<Response>;
|
|
262
|
+
errMsgs?: FetchErrMsgs;
|
|
263
|
+
/**
|
|
264
|
+
* Interceptor/transformer callback executed at different stages of the request.
|
|
265
|
+
* See {@link FetchInterceptors} for more details.
|
|
266
|
+
*/
|
|
267
|
+
interceptors?: FetchInterceptors;
|
|
268
|
+
/** Request timeout in milliseconds */
|
|
269
|
+
timeout?: number;
|
|
270
|
+
/** Whether to validate URL before making the request. Default: `true` */
|
|
271
|
+
validateUrl?: boolean;
|
|
272
|
+
} & FetchRetryOptions;
|
|
273
|
+
/** Default args */
|
|
274
|
+
type FetchDeferredArgs<OmitMethod extends boolean = false> = [
|
|
275
|
+
url?: string | URL,
|
|
276
|
+
options?: Omit<FetchOptions, 'abortCtrl' | (OmitMethod extends true ? 'method' : never)>
|
|
277
|
+
];
|
|
278
|
+
type FetchErrMsgs = {
|
|
279
|
+
/** Error message to be used when request is aborted without specifying a message */
|
|
280
|
+
aborted?: string;
|
|
281
|
+
/** Error message to be use when URL validation fails */
|
|
282
|
+
invalidUrl?: string;
|
|
283
|
+
/** Error message to be used when request parse failes */
|
|
284
|
+
parseFailed?: string;
|
|
285
|
+
/** Error message to be used when request times out */
|
|
286
|
+
timedout?: string;
|
|
287
|
+
/** Error message to be used when request fails */
|
|
288
|
+
requestFailed?: string;
|
|
289
|
+
};
|
|
260
290
|
/**
|
|
261
291
|
* Fetch request options
|
|
262
292
|
*/
|
|
263
293
|
type FetchOptions = Omit<RequestInit, 'body'> & FetchCustomOptions;
|
|
264
|
-
|
|
294
|
+
/** Default fetch options */
|
|
295
|
+
type FetchOptionsDefault = Omit<FetchOptionsInterceptor, 'abortCtrl' | 'as' | 'method' | 'signal' | 'timeout'> & {
|
|
296
|
+
/** Request timeout duration in milliseconds. Default: `30_000` (30 seconds) */
|
|
297
|
+
timeout: number;
|
|
298
|
+
};
|
|
265
299
|
/**
|
|
266
|
-
* Fetch options available to interceptors
|
|
300
|
+
* Fetch options available to interceptors.
|
|
301
|
+
*
|
|
267
302
|
*/
|
|
268
|
-
type FetchOptionsInterceptor = Omit<FetchOptions, 'as' | 'errMsgs' | 'interceptors' | 'headers' | keyof FetchRetryOptions> & {
|
|
303
|
+
type FetchOptionsInterceptor = Omit<FetchOptions, 'as' | 'errMsgs' | 'interceptors' | 'headers' | 'timeout' | keyof FetchRetryOptions> & {
|
|
269
304
|
as: FetchAs;
|
|
305
|
+
/** Error messages */
|
|
270
306
|
errMsgs: Required<FetchErrMsgs>;
|
|
271
307
|
headers: Headers;
|
|
308
|
+
/** Interceptors/transformers for fetch requests. See {@link FetchInterceptors} for more details. */
|
|
272
309
|
interceptors: Required<FetchInterceptors>;
|
|
310
|
+
timeout: number;
|
|
273
311
|
} & FetchRetryOptions;
|
|
274
312
|
/**
|
|
275
313
|
* Result types for specific parsers ("as": FetchAs)
|
|
@@ -297,10 +335,6 @@ type FetchRetryOptions = Omit<Partial<RetryOptions>, 'retry' | 'retryIf'> & {
|
|
|
297
335
|
retry?: number;
|
|
298
336
|
retryIf?: RetryIfFunc<Response>;
|
|
299
337
|
};
|
|
300
|
-
/**
|
|
301
|
-
* Generic fetch interceptor type
|
|
302
|
-
*/
|
|
303
|
-
type Interceptor<T, TArgs extends unknown[]> = (...args: [value: T, ...TArgs]) => ValueOrPromise<void> | ValueOrPromise<T>;
|
|
304
338
|
type PostBody = Record<string, unknown> | BodyInit | null;
|
|
305
339
|
type PostArgs<OmitMethod = false> = [
|
|
306
340
|
url: string | URL,
|
|
@@ -356,6 +390,21 @@ type PostOptions = {
|
|
|
356
390
|
method?: 'post' | 'put' | 'patch' | 'delete' | 'POST' | 'PUT' | 'PATCH' | 'DELETE';
|
|
357
391
|
} & Omit<FetchOptions, 'method'>;
|
|
358
392
|
|
|
393
|
+
/** Custom error message for fetch requests with more detailed info about the request URL, fetch options and response */
|
|
394
|
+
declare class FetchError extends Error {
|
|
395
|
+
/** Create a new `FetchError` with a new `message` while preserving all metadata */
|
|
396
|
+
clone: (newMessage: string) => FetchError;
|
|
397
|
+
options: FetchOptions;
|
|
398
|
+
response: Response | undefined;
|
|
399
|
+
url: string | URL;
|
|
400
|
+
constructor(message: string, options: {
|
|
401
|
+
cause?: unknown;
|
|
402
|
+
options: FetchOptions;
|
|
403
|
+
response?: Response;
|
|
404
|
+
url: string | URL;
|
|
405
|
+
});
|
|
406
|
+
}
|
|
407
|
+
|
|
359
408
|
/**
|
|
360
409
|
* Create a reusable fetch client with shared options. The returned function comes attached with a
|
|
361
410
|
* `.deferred()` function for debounce and throttle behavior.
|
|
@@ -417,8 +466,8 @@ declare const createClient: <FixedOpts extends FetchOptions | undefined, CommonO
|
|
|
417
466
|
fixedOptions?: FixedOpts,
|
|
418
467
|
/** Common fetch options that can be overriden by individual request */
|
|
419
468
|
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):
|
|
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]) =>
|
|
469
|
+
<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): _superutils_promise.IPromisE_Timeout<TReturn>;
|
|
470
|
+
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]) => _superutils_promise.IPromisE_Timeout<TReturn_1>;
|
|
422
471
|
};
|
|
423
472
|
|
|
424
473
|
/**
|
|
@@ -455,8 +504,9 @@ commonOptions?: FetchOptions & CommonOpts, commonDeferOptions?: DeferredAsyncOpt
|
|
|
455
504
|
* const updateProduct = postClient.deferred(
|
|
456
505
|
* {
|
|
457
506
|
* delayMs: 300, // debounce duration
|
|
507
|
+
* onResult: console.log, // prints only successful results
|
|
458
508
|
* },
|
|
459
|
-
* 'https://dummyjson.com/products/
|
|
509
|
+
* 'https://dummyjson.com/products/add',
|
|
460
510
|
* {
|
|
461
511
|
* method: 'patch',
|
|
462
512
|
* timeout: 3000,
|
|
@@ -471,24 +521,12 @@ declare const createPostClient: <FixedOpts extends PostOptions | undefined, Comm
|
|
|
471
521
|
fixedOptions?: FixedOpts,
|
|
472
522
|
/** Common fetch options that can be overriden by individual request */
|
|
473
523
|
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):
|
|
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>) =>
|
|
524
|
+
<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_Timeout<TReturn>;
|
|
525
|
+
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_Timeout<TReturn_1>;
|
|
476
526
|
};
|
|
477
527
|
|
|
478
|
-
/**
|
|
479
|
-
|
|
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
|
-
|
|
528
|
+
/** Node.js setTimeout limit is 2147483647 (2^31-1). Larger values fire immediately. */
|
|
529
|
+
declare const MAX_TIMEOUT = 2147483647;
|
|
492
530
|
/**
|
|
493
531
|
* Extended `fetch` with timeout, retry, and other options. Automatically parses as JSON by default on success.
|
|
494
532
|
*
|
|
@@ -508,9 +546,9 @@ declare const executeInterceptors: <T, TArgs extends unknown[]>(value: T, interc
|
|
|
508
546
|
* ```
|
|
509
547
|
*/
|
|
510
548
|
declare const fetch: {
|
|
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):
|
|
549
|
+
<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_Timeout<TReturn>;
|
|
512
550
|
/** Default fetch options */
|
|
513
|
-
defaults:
|
|
551
|
+
defaults: FetchOptionsDefault;
|
|
514
552
|
};
|
|
515
553
|
|
|
516
554
|
/**
|
|
@@ -528,7 +566,10 @@ declare const fetch: {
|
|
|
528
566
|
* .then(console.log, console.error)
|
|
529
567
|
* ```
|
|
530
568
|
*/
|
|
531
|
-
declare const fetchResponse:
|
|
569
|
+
declare const fetchResponse: {
|
|
570
|
+
<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_Timeout<TReturn>;
|
|
571
|
+
defaults: FetchOptionsDefault;
|
|
572
|
+
};
|
|
532
573
|
|
|
533
574
|
declare const methods: {
|
|
534
575
|
/** Make HTTP requests with method GET */
|
|
@@ -537,7 +578,7 @@ declare const methods: {
|
|
|
537
578
|
headers?: HeadersInit | undefined;
|
|
538
579
|
} & Omit<FetchOptions, "headers" | "method"> & Partial<Record<"method", never>>) | undefined = ({
|
|
539
580
|
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.
|
|
581
|
+
} & 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_Timeout<TReturn>;
|
|
541
582
|
deferred<ThisArg = unknown, Delay extends number = number, DefaultUrl extends FetchArgs[0] | undefined = string | URL | undefined, DefaultOptions extends ({
|
|
542
583
|
headers?: HeadersInit | undefined;
|
|
543
584
|
} & Omit<FetchOptions, "headers" | "method"> & Partial<Record<"method", never>>) | undefined = ({
|
|
@@ -546,7 +587,7 @@ declare const methods: {
|
|
|
546
587
|
headers?: HeadersInit | undefined;
|
|
547
588
|
} & Omit<FetchOptions, "headers" | "method"> & Partial<Record<"method", never>>) | undefined = ({
|
|
548
589
|
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.
|
|
590
|
+
} & 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_Timeout<TReturn>;
|
|
550
591
|
};
|
|
551
592
|
/** Make HTTP requests with method HEAD */
|
|
552
593
|
head: {
|
|
@@ -554,7 +595,7 @@ declare const methods: {
|
|
|
554
595
|
headers?: HeadersInit | undefined;
|
|
555
596
|
} & Omit<FetchOptions, "headers" | "method"> & Partial<Record<"method", never>>) | undefined = ({
|
|
556
597
|
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.
|
|
598
|
+
} & 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_Timeout<TReturn>;
|
|
558
599
|
deferred<ThisArg = unknown, Delay extends number = number, DefaultUrl extends FetchArgs[0] | undefined = string | URL | undefined, DefaultOptions extends ({
|
|
559
600
|
headers?: HeadersInit | undefined;
|
|
560
601
|
} & Omit<FetchOptions, "headers" | "method"> & Partial<Record<"method", never>>) | undefined = ({
|
|
@@ -563,7 +604,7 @@ declare const methods: {
|
|
|
563
604
|
headers?: HeadersInit | undefined;
|
|
564
605
|
} & Omit<FetchOptions, "headers" | "method"> & Partial<Record<"method", never>>) | undefined = ({
|
|
565
606
|
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.
|
|
607
|
+
} & 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_Timeout<TReturn>;
|
|
567
608
|
};
|
|
568
609
|
/** Make HTTP requests with method OPTIONS */
|
|
569
610
|
options: {
|
|
@@ -571,7 +612,7 @@ declare const methods: {
|
|
|
571
612
|
headers?: HeadersInit | undefined;
|
|
572
613
|
} & Omit<FetchOptions, "headers" | "method"> & Partial<Record<"method", never>>) | undefined = ({
|
|
573
614
|
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.
|
|
615
|
+
} & 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_Timeout<TReturn>;
|
|
575
616
|
deferred<ThisArg = unknown, Delay extends number = number, DefaultUrl extends FetchArgs[0] | undefined = string | URL | undefined, DefaultOptions extends ({
|
|
576
617
|
headers?: HeadersInit | undefined;
|
|
577
618
|
} & Omit<FetchOptions, "headers" | "method"> & Partial<Record<"method", never>>) | undefined = ({
|
|
@@ -580,7 +621,7 @@ declare const methods: {
|
|
|
580
621
|
headers?: HeadersInit | undefined;
|
|
581
622
|
} & Omit<FetchOptions, "headers" | "method"> & Partial<Record<"method", never>>) | undefined = ({
|
|
582
623
|
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.
|
|
624
|
+
} & 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_Timeout<TReturn>;
|
|
584
625
|
};
|
|
585
626
|
/** Make HTTP requests with method DELETE */
|
|
586
627
|
delete: {
|
|
@@ -588,14 +629,14 @@ declare const methods: {
|
|
|
588
629
|
headers?: HeadersInit | undefined;
|
|
589
630
|
} & Omit<PostOptions, "headers" | "method"> & Partial<Record<"method", never>>) | undefined = ({
|
|
590
631
|
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.
|
|
632
|
+
} & 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_Timeout<TReturn>;
|
|
592
633
|
deferred<ThisArg, Delay extends number, DefaultUrl extends PostArgs[0] | undefined, DefaultData extends PostArgs[1] = undefined, DefaultOptions extends ({
|
|
593
634
|
headers?: HeadersInit | undefined;
|
|
594
635
|
} & 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
636
|
headers?: HeadersInit | undefined;
|
|
596
637
|
} & Omit<PostOptions, "headers" | "method"> & Partial<Record<"method", never>>) | undefined = {
|
|
597
638
|
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.
|
|
639
|
+
} & 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_Timeout<TReturn>;
|
|
599
640
|
};
|
|
600
641
|
/** Make HTTP requests with method PATCH */
|
|
601
642
|
patch: {
|
|
@@ -603,14 +644,14 @@ declare const methods: {
|
|
|
603
644
|
headers?: HeadersInit | undefined;
|
|
604
645
|
} & Omit<PostOptions, "headers" | "method"> & Partial<Record<"method", never>>) | undefined = ({
|
|
605
646
|
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.
|
|
647
|
+
} & 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_Timeout<TReturn>;
|
|
607
648
|
deferred<ThisArg, Delay extends number, DefaultUrl extends PostArgs[0] | undefined, DefaultData extends PostArgs[1] = undefined, DefaultOptions extends ({
|
|
608
649
|
headers?: HeadersInit | undefined;
|
|
609
650
|
} & 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
651
|
headers?: HeadersInit | undefined;
|
|
611
652
|
} & Omit<PostOptions, "headers" | "method"> & Partial<Record<"method", never>>) | undefined = {
|
|
612
653
|
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.
|
|
654
|
+
} & 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_Timeout<TReturn>;
|
|
614
655
|
};
|
|
615
656
|
/** Make HTTP requests with method POST */
|
|
616
657
|
post: {
|
|
@@ -618,14 +659,14 @@ declare const methods: {
|
|
|
618
659
|
headers?: HeadersInit | undefined;
|
|
619
660
|
} & Omit<PostOptions, "headers" | "method"> & Partial<Record<"method", never>>) | undefined = ({
|
|
620
661
|
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.
|
|
662
|
+
} & 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_Timeout<TReturn>;
|
|
622
663
|
deferred<ThisArg, Delay extends number, DefaultUrl extends PostArgs[0] | undefined, DefaultData extends PostArgs[1] = undefined, DefaultOptions extends ({
|
|
623
664
|
headers?: HeadersInit | undefined;
|
|
624
665
|
} & 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
666
|
headers?: HeadersInit | undefined;
|
|
626
667
|
} & Omit<PostOptions, "headers" | "method"> & Partial<Record<"method", never>>) | undefined = {
|
|
627
668
|
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.
|
|
669
|
+
} & 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_Timeout<TReturn>;
|
|
629
670
|
};
|
|
630
671
|
/** Make HTTP requests with method PUT */
|
|
631
672
|
put: {
|
|
@@ -633,14 +674,14 @@ declare const methods: {
|
|
|
633
674
|
headers?: HeadersInit | undefined;
|
|
634
675
|
} & Omit<PostOptions, "headers" | "method"> & Partial<Record<"method", never>>) | undefined = ({
|
|
635
676
|
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.
|
|
677
|
+
} & 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_Timeout<TReturn>;
|
|
637
678
|
deferred<ThisArg, Delay extends number, DefaultUrl extends PostArgs[0] | undefined, DefaultData extends PostArgs[1] = undefined, DefaultOptions extends ({
|
|
638
679
|
headers?: HeadersInit | undefined;
|
|
639
680
|
} & 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
681
|
headers?: HeadersInit | undefined;
|
|
641
682
|
} & Omit<PostOptions, "headers" | "method"> & Partial<Record<"method", never>>) | undefined = {
|
|
642
683
|
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.
|
|
684
|
+
} & 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_Timeout<TReturn>;
|
|
644
685
|
};
|
|
645
686
|
};
|
|
646
687
|
/**
|
|
@@ -688,16 +729,29 @@ declare const methods: {
|
|
|
688
729
|
* @param url
|
|
689
730
|
* @param options (optional) Standard `fetch` options extended with {@link FetchCustomOptions}
|
|
690
731
|
* @param options.abortCtrl (optional) if not provided `AbortController` will be instantiated when `timeout` used.
|
|
691
|
-
*
|
|
732
|
+
*
|
|
733
|
+
* Default: `new AbortController()`
|
|
734
|
+
* @param options.as (optional) (optional) specify how to parse the result.
|
|
692
735
|
* For raw `Response` use {@link FetchAs.response}
|
|
736
|
+
*
|
|
737
|
+
* Default: {@link FetchAs.json}
|
|
693
738
|
* @param options.headers (optional) request headers
|
|
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.
|
|
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.
|
|
698
739
|
*
|
|
740
|
+
* Default: `{ 'content-type': 'application/json' }`
|
|
741
|
+
* @param options.interceptors (optional) request interceptor/transformer callbacks.
|
|
742
|
+
* See {@link FetchInterceptors} for details.
|
|
743
|
+
* @param options.method (optional) fetch method.
|
|
744
|
+
*
|
|
745
|
+
* Default: `'get'`
|
|
746
|
+
* @param options.timeout (optional) duration in milliseconds to abort the request.
|
|
747
|
+
* This duration includes the execution of all interceptors/transformers.
|
|
748
|
+
*
|
|
749
|
+
* Default: `30_000`
|
|
750
|
+
*
|
|
751
|
+
* ---
|
|
699
752
|
*
|
|
700
753
|
* @example Drop-in replacement for built-in fetch
|
|
754
|
+
*
|
|
701
755
|
* ```javascript
|
|
702
756
|
* import fetch from '@superutils/fetch'
|
|
703
757
|
*
|
|
@@ -729,27 +783,49 @@ declare const methods: {
|
|
|
729
783
|
* ```typescript
|
|
730
784
|
* import fetch from '@superutils/fetch'
|
|
731
785
|
*
|
|
732
|
-
*
|
|
733
|
-
*
|
|
734
|
-
*
|
|
735
|
-
*
|
|
736
|
-
*
|
|
737
|
-
*
|
|
738
|
-
*
|
|
739
|
-
*
|
|
740
|
-
*
|
|
741
|
-
*
|
|
742
|
-
*
|
|
743
|
-
*
|
|
744
|
-
*
|
|
745
|
-
*
|
|
746
|
-
*
|
|
747
|
-
*
|
|
748
|
-
*
|
|
749
|
-
*
|
|
786
|
+
* const { defaults, errorMsgs, interceptors } = fetch
|
|
787
|
+
*
|
|
788
|
+
* // set default request timeout duration in milliseconds
|
|
789
|
+
* defaults.timeout = 40_000
|
|
790
|
+
*
|
|
791
|
+
* // default headers
|
|
792
|
+
* defaults.headers = { 'content-type': 'text/plain' }
|
|
793
|
+
*
|
|
794
|
+
* // override error messages
|
|
795
|
+
* errorMsgs.invalidUrl = 'URL is not valid'
|
|
796
|
+
* errorMsgs.timedout = 'Request took longer than expected'
|
|
797
|
+
*
|
|
798
|
+
* // add an interceptor to log all request failures.
|
|
799
|
+
* const fetchLogger = (fetchErr, url, options) => console.log('Fetch error log', fetchErr)
|
|
800
|
+
* interceptors.error.push(fetchLogger)
|
|
801
|
+
*
|
|
802
|
+
* // add an interceptor to conditionally include header before making requests
|
|
803
|
+
* interceptors.request.push((url, options) => {
|
|
804
|
+
* // ignore login requests
|
|
805
|
+
* if (`${url}`.includes('/login')) return
|
|
806
|
+
*
|
|
807
|
+
* options.headers.set('x-auth-token', 'my-auth-token')
|
|
808
|
+
* })
|
|
750
809
|
* ```
|
|
751
810
|
*/
|
|
752
|
-
declare const
|
|
811
|
+
declare const defaultFetch: typeof fetchResponse & typeof methods;
|
|
812
|
+
|
|
813
|
+
/**
|
|
814
|
+
* Gracefully executes interceptors and returns the processed value.
|
|
815
|
+
* If the value is not transformed (by returning a new value) by the interceptors,
|
|
816
|
+
* the original value is returned.
|
|
817
|
+
*
|
|
818
|
+
* @param value value to be passed to the interceptors
|
|
819
|
+
* @param signal The AbortController used to monitor the request status. If the signal is aborted (e.g. due to
|
|
820
|
+
* timeout or manual cancellation), the interceptor chain halts immediately. Note: This does not interrupt the
|
|
821
|
+
* currently executing interceptor, but prevents subsequent ones from running.
|
|
822
|
+
* @param interceptors interceptor/transformer callbacks
|
|
823
|
+
* @param args (optional) common arguments to be supplied to all the interceptors in addition to
|
|
824
|
+
* the `value' which will always be the first argument.
|
|
825
|
+
*
|
|
826
|
+
* Interceptor arguments: `[value, ...args]`
|
|
827
|
+
*/
|
|
828
|
+
declare const executeInterceptors: <T, TArgs extends unknown[]>(value: T, signal?: AbortSignal, interceptors?: Interceptor<T, TArgs>[], ...args: TArgs) => Promise<T>;
|
|
753
829
|
|
|
754
830
|
/**
|
|
755
831
|
* Add AbortController to options if not present and propagate external abort signal if provided.
|
|
@@ -788,4 +864,4 @@ declare const mergeFetchOptions: (...allOptions: FetchOptions[]) => FetchOptions
|
|
|
788
864
|
/** Merges partial fetch options ignoring empty or undefined. Otherwise, will return the first argument. */
|
|
789
865
|
declare const mergePartialOptions: (...optionsAr: (Partial<FetchOptions> | undefined)[]) => Partial<FetchOptions> | undefined;
|
|
790
866
|
|
|
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
|
|
867
|
+
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 FetchOptionsDefault, type FetchOptionsInterceptor, type FetchResult, type FetchRetryOptions, type Interceptor, MAX_TIMEOUT, type PostArgs, type PostBody, type PostDeferredCbArgs, type PostOptions, createClient, createPostClient, defaultFetch as default, executeInterceptors, fetch, fetchResponse, getAbortCtrl, getResponse, mergeFetchOptions, mergePartialOptions };
|
package/dist/index.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// src/createClient.ts
|
|
2
|
-
import
|
|
2
|
+
import { deferredCallback } from "@superutils/promise";
|
|
3
3
|
|
|
4
4
|
// src/fetch.ts
|
|
5
5
|
import {
|
|
@@ -9,13 +9,16 @@ import {
|
|
|
9
9
|
isPromise,
|
|
10
10
|
isUrlValid
|
|
11
11
|
} from "@superutils/core";
|
|
12
|
-
import
|
|
12
|
+
import {
|
|
13
|
+
timeout as PromisE_timeout
|
|
14
|
+
} from "@superutils/promise";
|
|
13
15
|
|
|
14
16
|
// src/executeInterceptors.ts
|
|
15
17
|
import { fallbackIfFails, isFn } from "@superutils/core";
|
|
16
|
-
var executeInterceptors = async (value, interceptors, ...args) => {
|
|
18
|
+
var executeInterceptors = async (value, signal, interceptors, ...args) => {
|
|
17
19
|
var _a;
|
|
18
20
|
for (const interceptor of [...interceptors != null ? interceptors : []].filter(isFn)) {
|
|
21
|
+
if (signal == null ? void 0 : signal.aborted) return value;
|
|
19
22
|
value = (_a = await fallbackIfFails(
|
|
20
23
|
interceptor,
|
|
21
24
|
[value, ...args],
|
|
@@ -46,13 +49,13 @@ var getAbortCtrl = (options) => {
|
|
|
46
49
|
|
|
47
50
|
// src/getResponse.ts
|
|
48
51
|
import { fallbackIfFails as fallbackIfFails2, isPositiveInteger } from "@superutils/core";
|
|
49
|
-
import
|
|
52
|
+
import { retry } from "@superutils/promise";
|
|
50
53
|
var getResponse = async (url, options = {}) => {
|
|
51
|
-
const fetchFunc = globalThis.fetch;
|
|
54
|
+
const { abortCtrl, fetchFunc = globalThis.fetch } = options;
|
|
52
55
|
if (!isPositiveInteger(options.retry))
|
|
53
56
|
return fetchFunc(url, options);
|
|
54
57
|
let attemptCount = 0;
|
|
55
|
-
const response =
|
|
58
|
+
const response = retry(
|
|
56
59
|
() => {
|
|
57
60
|
attemptCount++;
|
|
58
61
|
return fetchFunc(url, options);
|
|
@@ -61,6 +64,7 @@ var getResponse = async (url, options = {}) => {
|
|
|
61
64
|
...options,
|
|
62
65
|
retryIf: async (res, count, error) => {
|
|
63
66
|
var _a, _b;
|
|
67
|
+
if (abortCtrl == null ? void 0 : abortCtrl.signal.aborted) return false;
|
|
64
68
|
const failed = !!error || !(res == null ? void 0 : res.ok);
|
|
65
69
|
return !!((_b = await fallbackIfFails2(
|
|
66
70
|
(_a = options == null ? void 0 : options.retryIf) != null ? _a : failed,
|
|
@@ -84,7 +88,7 @@ var getResponse_default = getResponse;
|
|
|
84
88
|
import { isEmpty, isObj, objKeys } from "@superutils/core";
|
|
85
89
|
var mergeFetchOptions = (...allOptions) => allOptions.reduce(
|
|
86
90
|
(merged, next) => {
|
|
87
|
-
var _a, _b, _c, _d, _e, _f, _g, _h, _i
|
|
91
|
+
var _a, _b, _c, _d, _e, _f, _g, _h, _i;
|
|
88
92
|
next = isObj(next) ? next : {};
|
|
89
93
|
const { errMsgs = {}, headers, interceptors: ints1 = {} } = merged;
|
|
90
94
|
const { errMsgs: msgs2 = {}, interceptors: ints2 = {} } = next;
|
|
@@ -114,7 +118,7 @@ var mergeFetchOptions = (...allOptions) => allOptions.reduce(
|
|
|
114
118
|
...(_h = ints2 == null ? void 0 : ints2.result) != null ? _h : []
|
|
115
119
|
]
|
|
116
120
|
},
|
|
117
|
-
timeout: (
|
|
121
|
+
timeout: (_i = next.timeout) != null ? _i : merged.timeout
|
|
118
122
|
};
|
|
119
123
|
},
|
|
120
124
|
{ headers: new Headers() }
|
|
@@ -125,11 +129,7 @@ var mergePartialOptions = (...optionsAr) => {
|
|
|
125
129
|
return optionsAr.length <= 1 ? optionsAr[0] : mergeFetchOptions(...optionsAr);
|
|
126
130
|
};
|
|
127
131
|
|
|
128
|
-
// src/types.ts
|
|
129
|
-
import {
|
|
130
|
-
ResolveError,
|
|
131
|
-
ResolveIgnored
|
|
132
|
-
} from "@superutils/promise";
|
|
132
|
+
// src/types/constants.ts
|
|
133
133
|
var ContentType = {
|
|
134
134
|
APPLICATION_JAVASCRIPT: "application/javascript",
|
|
135
135
|
APPLICATION_JSON: "application/json",
|
|
@@ -155,56 +155,99 @@ var FetchAs = /* @__PURE__ */ ((FetchAs2) => {
|
|
|
155
155
|
FetchAs2["text"] = "text";
|
|
156
156
|
return FetchAs2;
|
|
157
157
|
})(FetchAs || {});
|
|
158
|
+
|
|
159
|
+
// src/types/FetchError.ts
|
|
158
160
|
var FetchError = class _FetchError extends Error {
|
|
159
161
|
constructor(message, options) {
|
|
160
162
|
super(message, { cause: options.cause });
|
|
161
|
-
this.clone = (newMessage) => new _FetchError(newMessage, {
|
|
162
|
-
cause: this.cause,
|
|
163
|
-
options: this.options,
|
|
164
|
-
response: this.response,
|
|
165
|
-
url: this.url
|
|
166
|
-
});
|
|
167
163
|
this.name = "FetchError";
|
|
168
|
-
this
|
|
169
|
-
|
|
170
|
-
|
|
164
|
+
Object.defineProperties(this, {
|
|
165
|
+
clone: {
|
|
166
|
+
get() {
|
|
167
|
+
return (newMessage) => new _FetchError(newMessage, {
|
|
168
|
+
cause: options.cause,
|
|
169
|
+
options: options.options,
|
|
170
|
+
response: options.response,
|
|
171
|
+
url: options.url
|
|
172
|
+
});
|
|
173
|
+
}
|
|
174
|
+
},
|
|
175
|
+
options: {
|
|
176
|
+
get() {
|
|
177
|
+
return options.options;
|
|
178
|
+
}
|
|
179
|
+
},
|
|
180
|
+
response: {
|
|
181
|
+
get() {
|
|
182
|
+
return options.response;
|
|
183
|
+
}
|
|
184
|
+
},
|
|
185
|
+
url: {
|
|
186
|
+
get() {
|
|
187
|
+
return options.url;
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
});
|
|
171
191
|
}
|
|
172
192
|
};
|
|
173
193
|
|
|
194
|
+
// src/types/options.ts
|
|
195
|
+
import {
|
|
196
|
+
ResolveError,
|
|
197
|
+
ResolveIgnored
|
|
198
|
+
} from "@superutils/promise";
|
|
199
|
+
|
|
174
200
|
// src/fetch.ts
|
|
201
|
+
var MAX_TIMEOUT = 2147483647;
|
|
175
202
|
var fetch = (url, options = {}) => {
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
const
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
203
|
+
var _a, _b, _c;
|
|
204
|
+
let errResponse;
|
|
205
|
+
const _options = mergeFetchOptions_default(fetch.defaults, options);
|
|
206
|
+
_options.abortCtrl = getAbortCtrl(_options);
|
|
207
|
+
(_a = _options.as) != null ? _a : _options.as = "json" /* json */;
|
|
208
|
+
(_b = _options.method) != null ? _b : _options.method = "get";
|
|
209
|
+
(_c = _options.signal) != null ? _c : _options.signal = _options.abortCtrl.signal;
|
|
210
|
+
_options.timeout = Math.min(
|
|
211
|
+
isPositiveNumber(_options.timeout) ? _options.timeout : fetch.defaults.timeout,
|
|
212
|
+
MAX_TIMEOUT
|
|
213
|
+
);
|
|
214
|
+
const { abortCtrl, as: parseAs, headers, timeout } = _options;
|
|
215
|
+
let contentType = headers.get("content-type");
|
|
216
|
+
if (!contentType) {
|
|
217
|
+
headers.set("content-type", ContentType.APPLICATION_JSON);
|
|
218
|
+
contentType = ContentType.APPLICATION_JSON;
|
|
219
|
+
}
|
|
220
|
+
const processErr = (err) => {
|
|
221
|
+
var _a2, _b2, _c2, _d, _e;
|
|
222
|
+
let msg = (_a2 = err == null ? void 0 : err.message) != null ? _a2 : err;
|
|
223
|
+
if ((err == null ? void 0 : err.name) === "AbortError") msg = (_c2 = (_b2 = _options.errMsgs) == null ? void 0 : _b2.aborted) != null ? _c2 : msg;
|
|
224
|
+
return executeInterceptors_default(
|
|
225
|
+
new FetchError(msg, {
|
|
226
|
+
cause: (_d = err == null ? void 0 : err.cause) != null ? _d : err,
|
|
227
|
+
response: errResponse,
|
|
228
|
+
options: _options,
|
|
229
|
+
url
|
|
230
|
+
}),
|
|
231
|
+
void 0,
|
|
232
|
+
// should execute regardless of abort status
|
|
233
|
+
(_e = _options.interceptors) == null ? void 0 : _e.error,
|
|
190
234
|
url,
|
|
191
|
-
_options.interceptors.request,
|
|
192
235
|
_options
|
|
193
|
-
);
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
errMsgs,
|
|
198
|
-
timeout,
|
|
199
|
-
validateUrl = true
|
|
200
|
-
} = _options;
|
|
201
|
-
if (isPositiveNumber(timeout)) {
|
|
202
|
-
timeoutId = setTimeout(() => abortCtrl.abort(), timeout);
|
|
203
|
-
}
|
|
204
|
-
if (_options.abortCtrl) _options.signal = _options.abortCtrl.signal;
|
|
236
|
+
).then((err2) => Promise.reject(err2));
|
|
237
|
+
};
|
|
238
|
+
const start = async () => {
|
|
239
|
+
var _a2, _b2, _c2, _d;
|
|
205
240
|
try {
|
|
241
|
+
url = await executeInterceptors_default(
|
|
242
|
+
url,
|
|
243
|
+
abortCtrl.signal,
|
|
244
|
+
(_a2 = _options.interceptors) == null ? void 0 : _a2.request,
|
|
245
|
+
_options
|
|
246
|
+
);
|
|
247
|
+
const { body, errMsgs, validateUrl = true } = _options;
|
|
248
|
+
(_b2 = _options.signal) != null ? _b2 : _options.signal = abortCtrl.signal;
|
|
206
249
|
if (validateUrl && !isUrlValid(url, false))
|
|
207
|
-
|
|
250
|
+
return processErr(new Error(errMsgs.invalidUrl));
|
|
208
251
|
const shouldStringifyBody = [
|
|
209
252
|
ContentType.APPLICATION_JSON,
|
|
210
253
|
ContentType.APPLICATION_X_WWW_FORM_URLENCODED
|
|
@@ -216,7 +259,8 @@ var fetch = (url, options = {}) => {
|
|
|
216
259
|
let response = await getResponse_default(url, _options);
|
|
217
260
|
response = await executeInterceptors_default(
|
|
218
261
|
response,
|
|
219
|
-
|
|
262
|
+
abortCtrl.signal,
|
|
263
|
+
(_c2 = _options.interceptors) == null ? void 0 : _c2.response,
|
|
220
264
|
url,
|
|
221
265
|
_options
|
|
222
266
|
);
|
|
@@ -224,83 +268,69 @@ var fetch = (url, options = {}) => {
|
|
|
224
268
|
const { status = 0 } = response;
|
|
225
269
|
const isSuccess = status >= 200 && status < 300;
|
|
226
270
|
if (!isSuccess) {
|
|
227
|
-
const fallbackMsg = `${errMsgs.requestFailed} ${status}`;
|
|
228
271
|
const jsonError = await fallbackIfFails3(
|
|
229
272
|
// try to parse error response as json first
|
|
230
273
|
() => response.json(),
|
|
231
274
|
[],
|
|
232
275
|
void 0
|
|
233
276
|
);
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
cause: jsonError
|
|
237
|
-
|
|
277
|
+
throw new Error(
|
|
278
|
+
(jsonError == null ? void 0 : jsonError.message) || `${errMsgs.requestFailed} ${status}`,
|
|
279
|
+
{ cause: jsonError }
|
|
280
|
+
);
|
|
238
281
|
}
|
|
239
|
-
let result = response;
|
|
240
282
|
const parseFunc = response[parseAs];
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
}
|
|
283
|
+
let result = !isFn2(parseFunc) ? response : parseFunc.bind(response)();
|
|
284
|
+
if (isPromise(result))
|
|
285
|
+
result = await result.catch(
|
|
286
|
+
(err) => Promise.reject(
|
|
287
|
+
new Error(
|
|
288
|
+
`${errMsgs.parseFailed} ${parseAs}. ${err == null ? void 0 : err.message}`,
|
|
289
|
+
{ cause: err }
|
|
290
|
+
)
|
|
291
|
+
)
|
|
292
|
+
);
|
|
252
293
|
result = await executeInterceptors_default(
|
|
253
294
|
result,
|
|
254
|
-
|
|
295
|
+
abortCtrl.signal,
|
|
296
|
+
(_d = _options.interceptors) == null ? void 0 : _d.result,
|
|
255
297
|
url,
|
|
256
298
|
_options
|
|
257
299
|
);
|
|
258
|
-
|
|
259
|
-
} catch (
|
|
260
|
-
|
|
261
|
-
const msg = (errX == null ? void 0 : errX.name) === "AbortError" ? errMsgs.reqTimedout : err == null ? void 0 : err.message;
|
|
262
|
-
let error = new FetchError(msg, {
|
|
263
|
-
cause: (_c = errX == null ? void 0 : errX.cause) != null ? _c : err,
|
|
264
|
-
response: errResponse,
|
|
265
|
-
options: _options,
|
|
266
|
-
url
|
|
267
|
-
});
|
|
268
|
-
error = await executeInterceptors_default(
|
|
269
|
-
error,
|
|
270
|
-
_options.interceptors.error,
|
|
271
|
-
url,
|
|
272
|
-
_options
|
|
273
|
-
);
|
|
274
|
-
reject(error);
|
|
300
|
+
return result;
|
|
301
|
+
} catch (_err) {
|
|
302
|
+
return processErr(_err);
|
|
275
303
|
}
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
304
|
+
};
|
|
305
|
+
return PromisE_timeout(
|
|
306
|
+
{
|
|
307
|
+
...options,
|
|
308
|
+
abortCtrl,
|
|
309
|
+
onAbort: () => processErr(new Error(_options.errMsgs.aborted)),
|
|
310
|
+
onTimeout: async () => processErr(new Error(_options.errMsgs.timedout)),
|
|
311
|
+
signal: _options.signal,
|
|
312
|
+
timeout
|
|
313
|
+
},
|
|
314
|
+
start
|
|
315
|
+
);
|
|
280
316
|
};
|
|
281
317
|
fetch.defaults = {
|
|
282
318
|
errMsgs: {
|
|
319
|
+
aborted: "Request aborted",
|
|
283
320
|
invalidUrl: "Invalid URL",
|
|
284
321
|
parseFailed: "Failed to parse response as",
|
|
285
|
-
|
|
322
|
+
timedout: "Request timed out",
|
|
286
323
|
requestFailed: "Request failed with status code:"
|
|
287
324
|
},
|
|
288
325
|
// all error messages must be defined here
|
|
289
326
|
headers: new Headers(),
|
|
290
|
-
/** Global interceptors for fetch requests */
|
|
291
327
|
interceptors: {
|
|
292
|
-
/**
|
|
293
|
-
* Global error interceptors to be invoked whenever an exception occurs
|
|
294
|
-
* Returning an
|
|
295
|
-
*/
|
|
296
328
|
error: [],
|
|
297
|
-
/** Interceptors to be invoked before making fetch requests */
|
|
298
329
|
request: [],
|
|
299
330
|
response: [],
|
|
300
331
|
result: []
|
|
301
332
|
},
|
|
302
|
-
|
|
303
|
-
timeout: 0,
|
|
333
|
+
timeout: 3e4,
|
|
304
334
|
validateUrl: true
|
|
305
335
|
};
|
|
306
336
|
var fetch_default = fetch;
|
|
@@ -336,7 +366,7 @@ var createClient = (fixedOptions, commonOptions, commonDeferOptions) => {
|
|
|
336
366
|
promise.onEarlyFinalize.push(() => _abortCtrl == null ? void 0 : _abortCtrl.abort());
|
|
337
367
|
return promise;
|
|
338
368
|
};
|
|
339
|
-
return
|
|
369
|
+
return deferredCallback(fetchCb, {
|
|
340
370
|
...commonDeferOptions,
|
|
341
371
|
...deferOptions
|
|
342
372
|
});
|
|
@@ -346,9 +376,9 @@ var createClient = (fixedOptions, commonOptions, commonDeferOptions) => {
|
|
|
346
376
|
var createClient_default = createClient;
|
|
347
377
|
|
|
348
378
|
// src/createPostClient.ts
|
|
349
|
-
import
|
|
379
|
+
import { deferredCallback as deferredCallback2 } from "@superutils/promise";
|
|
350
380
|
var createPostClient = (fixedOptions, commonOptions, commonDeferOptions) => {
|
|
351
|
-
const
|
|
381
|
+
const client = (url, data, options) => {
|
|
352
382
|
var _a;
|
|
353
383
|
const _options = mergePartialOptions(
|
|
354
384
|
commonOptions,
|
|
@@ -359,7 +389,7 @@ var createPostClient = (fixedOptions, commonOptions, commonDeferOptions) => {
|
|
|
359
389
|
(_a = _options.method) != null ? _a : _options.method = "post";
|
|
360
390
|
return fetch_default(url, _options);
|
|
361
391
|
};
|
|
362
|
-
|
|
392
|
+
client.deferred = (deferOptions = {}, defaultUrl, defaultData, defaultOptions) => {
|
|
363
393
|
let _abortCtrl;
|
|
364
394
|
const postCb = (...args) => {
|
|
365
395
|
var _a, _b, _c, _d;
|
|
@@ -379,16 +409,14 @@ var createPostClient = (fixedOptions, commonOptions, commonDeferOptions) => {
|
|
|
379
409
|
promise.onEarlyFinalize.push(() => _abortCtrl == null ? void 0 : _abortCtrl.abort());
|
|
380
410
|
return promise;
|
|
381
411
|
};
|
|
382
|
-
return
|
|
412
|
+
return deferredCallback2(postCb, {
|
|
383
413
|
...commonDeferOptions,
|
|
384
414
|
...deferOptions
|
|
385
415
|
});
|
|
386
416
|
};
|
|
387
|
-
return
|
|
417
|
+
return client;
|
|
388
418
|
};
|
|
389
419
|
var createPostClient_default = createPostClient;
|
|
390
|
-
var client = createPostClient();
|
|
391
|
-
client.deferred();
|
|
392
420
|
|
|
393
421
|
// src/fetchResponse.ts
|
|
394
422
|
var fetchResponse = (url, options) => {
|
|
@@ -397,9 +425,18 @@ var fetchResponse = (url, options) => {
|
|
|
397
425
|
(_a = options.as) != null ? _a : options.as = "response" /* response */;
|
|
398
426
|
return fetch_default(url, options);
|
|
399
427
|
};
|
|
428
|
+
fetchResponse.defaults = fetch_default.defaults;
|
|
429
|
+
Object.defineProperty(fetchResponse, "defaults", {
|
|
430
|
+
get() {
|
|
431
|
+
return fetch_default.defaults;
|
|
432
|
+
},
|
|
433
|
+
set(newDefaults) {
|
|
434
|
+
fetch_default.defaults = newDefaults;
|
|
435
|
+
}
|
|
436
|
+
});
|
|
400
437
|
var fetchResponse_default = fetchResponse;
|
|
401
438
|
|
|
402
|
-
// src/
|
|
439
|
+
// src/defaultFetch.ts
|
|
403
440
|
var methods = {
|
|
404
441
|
/** Make HTTP requests with method GET */
|
|
405
442
|
get: createClient_default({ method: "get" }),
|
|
@@ -416,31 +453,23 @@ var methods = {
|
|
|
416
453
|
/** Make HTTP requests with method PUT */
|
|
417
454
|
put: createPostClient_default({ method: "put" })
|
|
418
455
|
};
|
|
419
|
-
var
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
fetchDefault.delete = methods.delete;
|
|
429
|
-
fetchDefault.get = methods.get;
|
|
430
|
-
fetchDefault.head = methods.head;
|
|
431
|
-
fetchDefault.options = methods.options;
|
|
432
|
-
fetchDefault.patch = methods.patch;
|
|
433
|
-
fetchDefault.post = methods.post;
|
|
434
|
-
fetchDefault.put = methods.put;
|
|
435
|
-
var fetchDefault_default = fetchDefault;
|
|
456
|
+
var defaultFetch = fetchResponse_default;
|
|
457
|
+
defaultFetch.delete = methods.delete;
|
|
458
|
+
defaultFetch.get = methods.get;
|
|
459
|
+
defaultFetch.head = methods.head;
|
|
460
|
+
defaultFetch.options = methods.options;
|
|
461
|
+
defaultFetch.patch = methods.patch;
|
|
462
|
+
defaultFetch.post = methods.post;
|
|
463
|
+
defaultFetch.put = methods.put;
|
|
464
|
+
var defaultFetch_default = defaultFetch;
|
|
436
465
|
|
|
437
466
|
// src/index.ts
|
|
438
|
-
var index_default =
|
|
439
|
-
fetchDefault_default.get;
|
|
467
|
+
var index_default = defaultFetch_default;
|
|
440
468
|
export {
|
|
441
469
|
ContentType,
|
|
442
470
|
FetchAs,
|
|
443
471
|
FetchError,
|
|
472
|
+
MAX_TIMEOUT,
|
|
444
473
|
ResolveError,
|
|
445
474
|
ResolveIgnored,
|
|
446
475
|
createClient,
|
package/package.json
CHANGED
|
@@ -5,8 +5,8 @@
|
|
|
5
5
|
},
|
|
6
6
|
"description": "A lightweight `fetch` wrapper for browsers and Node.js, designed to simplify data fetching and reduce boilerplate.",
|
|
7
7
|
"dependencies": {
|
|
8
|
-
"@superutils/core": "^1.1.
|
|
9
|
-
"@superutils/promise": "^1.
|
|
8
|
+
"@superutils/core": "^1.1.8",
|
|
9
|
+
"@superutils/promise": "^1.2.0"
|
|
10
10
|
},
|
|
11
11
|
"files": [
|
|
12
12
|
"dist",
|
|
@@ -24,8 +24,8 @@
|
|
|
24
24
|
"main": "dist/index.js",
|
|
25
25
|
"name": "@superutils/fetch",
|
|
26
26
|
"peerDependencies": {
|
|
27
|
-
"@superutils/core": "^1.
|
|
28
|
-
"@superutils/promise": "^1.1.
|
|
27
|
+
"@superutils/core": "^1.2.0",
|
|
28
|
+
"@superutils/promise": "^1.1.7"
|
|
29
29
|
},
|
|
30
30
|
"publishConfig": {
|
|
31
31
|
"access": "public"
|
|
@@ -45,5 +45,5 @@
|
|
|
45
45
|
"sideEffects": false,
|
|
46
46
|
"type": "module",
|
|
47
47
|
"types": "dist/index.d.ts",
|
|
48
|
-
"version": "1.
|
|
48
|
+
"version": "1.3.0"
|
|
49
49
|
}
|