@superutils/fetch 1.4.2 → 1.5.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 +7 -7
- package/dist/browser/index.min.js +1124 -0
- package/dist/browser/index.min.js.map +1 -0
- package/dist/index.cjs +477 -0
- package/dist/index.d.cts +915 -0
- package/dist/index.d.ts +189 -183
- package/dist/index.js +97 -119
- package/package.json +15 -7
package/dist/index.d.cts
ADDED
|
@@ -0,0 +1,915 @@
|
|
|
1
|
+
import * as _superutils_promise from '@superutils/promise';
|
|
2
|
+
import { RetryOptions, RetryIfFunc, TimeoutOptions, IPromisE_Timeout, DeferredAsyncOptions } from '@superutils/promise';
|
|
3
|
+
export { DeferredAsyncOptions, ResolveError, ResolveIgnored, TIMEOUT_FALLBACK, TIMEOUT_MAX, TimeoutPromise } from '@superutils/promise';
|
|
4
|
+
import { ValueOrPromise, DropFirst } from '@superutils/core';
|
|
5
|
+
|
|
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
|
+
declare enum FetchAs {
|
|
23
|
+
arrayBuffer = "arrayBuffer",
|
|
24
|
+
blob = "blob",
|
|
25
|
+
bytes = "bytes",
|
|
26
|
+
formData = "formData",
|
|
27
|
+
json = "json",
|
|
28
|
+
response = "response",
|
|
29
|
+
text = "text"
|
|
30
|
+
}
|
|
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>;
|
|
36
|
+
/**
|
|
37
|
+
* Fetch error interceptor to be invoked whenever an exception occurs.
|
|
38
|
+
* This interceptor can also be used as the error transformer by returning {@link FetchError}.
|
|
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
|
+
*
|
|
43
|
+
* @param {FetchError} fetchError custom error that also contain URL, options & response
|
|
44
|
+
*
|
|
45
|
+
* @returns returning undefined or not returning anything will not override the error
|
|
46
|
+
*
|
|
47
|
+
* @example intercept fetch errors to log errors
|
|
48
|
+
* ```typescript
|
|
49
|
+
* import PromisE from '@superutils/promise'
|
|
50
|
+
*
|
|
51
|
+
* // not returning anything or returning undefined will avoid transforming the error.
|
|
52
|
+
* const logError = fetchErr => console.log(fetchErr)
|
|
53
|
+
* const result = await PromisE.fetch('https://my.domain.com/api/that/fails', {
|
|
54
|
+
* interceptors: {
|
|
55
|
+
* error: [logError]
|
|
56
|
+
* }
|
|
57
|
+
* })
|
|
58
|
+
* ```
|
|
59
|
+
*
|
|
60
|
+
* @example intercept & transform fetch errors
|
|
61
|
+
* ```typescript
|
|
62
|
+
* import PromisE from '@superutils/promise'
|
|
63
|
+
*
|
|
64
|
+
* // Interceptors can be async functions or just return a promise that resolves to the error.
|
|
65
|
+
* // If the execution of the interceptor fails or promise rejects, it will be ignored.
|
|
66
|
+
* // To transform the error it must directly return an error or a Promise that `resolves` with an error.
|
|
67
|
+
* const transformError = async (fetchErr, url, options) => {
|
|
68
|
+
* fetchErr.message = 'Custom errormessage'
|
|
69
|
+
* return Promise.resolve(fetchErr)
|
|
70
|
+
* }
|
|
71
|
+
* const result = await PromisE.fetch('https://my.domain.com/api/that/fails', {
|
|
72
|
+
* interceptors: {
|
|
73
|
+
* error: [transformError]
|
|
74
|
+
* }
|
|
75
|
+
* })
|
|
76
|
+
* ```
|
|
77
|
+
*/
|
|
78
|
+
type FetchInterceptorError = Interceptor<FetchError, FetchArgsInterceptor>;
|
|
79
|
+
/**
|
|
80
|
+
* Fetch request interceptor to be invoked before making a fetch request.
|
|
81
|
+
* This interceptor can also be used as a transformer:
|
|
82
|
+
* 1. by returning an API URL (string/URL)
|
|
83
|
+
* 2. by modifying the properties of the options parameter to be used before making the fetch request
|
|
84
|
+
*
|
|
85
|
+
* @example intercept and transform fetch request
|
|
86
|
+
* ```typescript
|
|
87
|
+
* import PromisE from '@superutils/promise'
|
|
88
|
+
*
|
|
89
|
+
* // update API version number
|
|
90
|
+
* const apiV1ToV2 = url => `${url}`.replace('api/v1', 'api/v2')
|
|
91
|
+
* const includeAuthToken = (url, options) => {
|
|
92
|
+
* options.headers.set('x-auth-token', 'my-auth-token')
|
|
93
|
+
* }
|
|
94
|
+
* const data = await PromisE.fetch('https://my.domain.com/api', {
|
|
95
|
+
* interceptors: {
|
|
96
|
+
* result: [apiV1ToV2, includeAuthToken]
|
|
97
|
+
* }
|
|
98
|
+
* })
|
|
99
|
+
* ```
|
|
100
|
+
*/
|
|
101
|
+
type FetchInterceptorRequest = Interceptor<FetchArgs[0], [
|
|
102
|
+
FetchArgsInterceptor[1]
|
|
103
|
+
]>;
|
|
104
|
+
/**
|
|
105
|
+
* Fetch response interceptor to be invoked before making a fetch request.
|
|
106
|
+
*
|
|
107
|
+
* This interceptor can also be used as a transformer by return a different/modified {@link Response}.
|
|
108
|
+
*
|
|
109
|
+
* @example intercept and transform response:
|
|
110
|
+
* ```typescript
|
|
111
|
+
* import PromisE from '@superutils/promise'
|
|
112
|
+
*
|
|
113
|
+
* // After successful login, retrieve user balance.
|
|
114
|
+
* // This is probably better suited as a result transformer but play along as this is
|
|
115
|
+
* // just a hypothetical scenario ;)
|
|
116
|
+
* const includeBalance = async response => {
|
|
117
|
+
* const balance = await PromisE.fetch('https://my.domain.com/api/user/12325345/balance')
|
|
118
|
+
* const user = await response.json()
|
|
119
|
+
* user.balance = balance
|
|
120
|
+
* return new Response(JSON.stringify(user))
|
|
121
|
+
* }
|
|
122
|
+
* const user = await PromisE.fetch('https://my.domain.com/api/login', {
|
|
123
|
+
* interceptors: {
|
|
124
|
+
* response: [includeBalance]
|
|
125
|
+
* }
|
|
126
|
+
* })
|
|
127
|
+
* ```
|
|
128
|
+
*/
|
|
129
|
+
type FetchInterceptorResponse = Interceptor<Response, FetchArgsInterceptor>;
|
|
130
|
+
/**
|
|
131
|
+
*
|
|
132
|
+
* Fetch result interceptor to be invoked before returning parsed fetch result.
|
|
133
|
+
*
|
|
134
|
+
* Result interceptors are executed ONLY when a result is successfully parsed (as ArrayBuffer, Blob, JSON, Text...).
|
|
135
|
+
* Result interceptors WILL NOT be executed if:
|
|
136
|
+
* - return type is set to `Response` by using {@link FetchAs.response} in the {@link FetchOptions.as}
|
|
137
|
+
* - exceptions is thrown even before attempting to parse
|
|
138
|
+
* - parse fails
|
|
139
|
+
*
|
|
140
|
+
* This interceptor can also be used as a transformer by returns a different/modified result.
|
|
141
|
+
*
|
|
142
|
+
*
|
|
143
|
+
* @example intercept and transform fetch result
|
|
144
|
+
* ```typescript
|
|
145
|
+
* import PromisE from '@superutils/promise'
|
|
146
|
+
*
|
|
147
|
+
* // first transform result by extracting result.data
|
|
148
|
+
* const extractData = result => result?.data ?? result
|
|
149
|
+
* // then check convert hexadecimal number to BigInt
|
|
150
|
+
* const hexToBigInt = data => {
|
|
151
|
+
* if (data.hasOwnProperty('balance') && `${data.balance}`.startsWith('0x')) {
|
|
152
|
+
* data.balance = BigInt(data.balance)
|
|
153
|
+
* }
|
|
154
|
+
* return data
|
|
155
|
+
* }
|
|
156
|
+
* // then log balance (no transformation)
|
|
157
|
+
* const logBalance = data => {
|
|
158
|
+
* data?.hasOwnProperty('balance') && console.log(data.balance)
|
|
159
|
+
* }
|
|
160
|
+
* const data = await PromisE.fetch('https://my.domain.com/api', {
|
|
161
|
+
* interceptors: {
|
|
162
|
+
* result: [
|
|
163
|
+
* extractData,
|
|
164
|
+
* hexToBigInt,
|
|
165
|
+
* logBalance
|
|
166
|
+
* ]
|
|
167
|
+
* }
|
|
168
|
+
* })
|
|
169
|
+
* ```
|
|
170
|
+
*/
|
|
171
|
+
type FetchInterceptorResult<Args extends unknown[] = FetchArgsInterceptor> = Interceptor<unknown, Args>;
|
|
172
|
+
/**
|
|
173
|
+
* All valid interceptors for fetch requests are:
|
|
174
|
+
* ---
|
|
175
|
+
* 1. error
|
|
176
|
+
* 2. request
|
|
177
|
+
* 3. response
|
|
178
|
+
* 4. result
|
|
179
|
+
*
|
|
180
|
+
* An interceptor can be any of the following:
|
|
181
|
+
* ---
|
|
182
|
+
* 1. synchronous function
|
|
183
|
+
* 2. synchronous function that returns a promise (or sometimes returns a promise)
|
|
184
|
+
* 3. asynchronous functions
|
|
185
|
+
*
|
|
186
|
+
* An interceptor can return:
|
|
187
|
+
* ---
|
|
188
|
+
* 1. undefined (void/no return): plain interceptor that does other stuff but does not transform
|
|
189
|
+
* 2. value: act as a transformer. Returned value depends on the type of interceptor.
|
|
190
|
+
* 3. promise resolves with (1) value or (2) undefined
|
|
191
|
+
*
|
|
192
|
+
* PS:
|
|
193
|
+
* ---
|
|
194
|
+
* 1. Any exception thrown by interceptors will gracefully ignored.
|
|
195
|
+
* 2. Interceptors will be executed in the sequence they're given.
|
|
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
|
|
198
|
+
*
|
|
199
|
+
* More info about specific interceptor types & examples:
|
|
200
|
+
* ---
|
|
201
|
+
* See the following for more details and examples:
|
|
202
|
+
*
|
|
203
|
+
* - `error`: {@link FetchInterceptorError}
|
|
204
|
+
* - `request`: {@link FetchInterceptorRequest}
|
|
205
|
+
* - `response`: {@link FetchInterceptorResponse}
|
|
206
|
+
* - `result`: {@link FetchInterceptorResult}
|
|
207
|
+
*/
|
|
208
|
+
type FetchInterceptors = {
|
|
209
|
+
/** Request error interceptors/transformers. See {@link FetchInterceptorError} for more details. */
|
|
210
|
+
error?: FetchInterceptorError | FetchInterceptorError[];
|
|
211
|
+
/** Request request interceptors/transformers. See {@link FetchInterceptorRequest} for more details. */
|
|
212
|
+
request?: FetchInterceptorRequest | FetchInterceptorRequest[];
|
|
213
|
+
/** Request response interceptors/transformers. See {@link FetchInterceptorResponse} for more details. */
|
|
214
|
+
response?: FetchInterceptorResponse | FetchInterceptorResponse[];
|
|
215
|
+
/** Request result interceptors/transformers. See {@link FetchInterceptorResult} for more details. */
|
|
216
|
+
result?: FetchInterceptorResult | FetchInterceptorResult[];
|
|
217
|
+
};
|
|
218
|
+
/** Interceptors after merging should only be array of functions */
|
|
219
|
+
type FetchInterceptorsMerged = {
|
|
220
|
+
error: FetchInterceptorError[];
|
|
221
|
+
request: FetchInterceptorRequest[];
|
|
222
|
+
response: FetchInterceptorResponse[];
|
|
223
|
+
result: FetchInterceptorResult[];
|
|
224
|
+
};
|
|
225
|
+
|
|
226
|
+
/** Exclude properties of `Target` from `Options`. `headers` will always be included */
|
|
227
|
+
type ExcludeOptions<Target, Options extends FetchOptions = FetchOptions> = Target extends FetchOptions ? {
|
|
228
|
+
headers?: Options['headers'];
|
|
229
|
+
} & Omit<Options, 'headers' | keyof Target> & Partial<Record<Exclude<keyof Target, 'headers'>, never>> : Options;
|
|
230
|
+
/** Exclude properties of `Target` from {@link PostOptions} */
|
|
231
|
+
type ExcludePostOptions<Target> = ExcludeOptions<Target, PostOptions>;
|
|
232
|
+
/** Extract the first macthing `FetchAs` from `T` array. If none matches, use `Fallback` */
|
|
233
|
+
type ExtractAs<T extends unknown[], //FetchOptions/FetchAs/...
|
|
234
|
+
Fallback = FetchAs.json> = T['length'] extends 0 ? Fallback : T[0] extends FetchAs ? T[0] : T[0] extends {
|
|
235
|
+
as: infer OptAs;
|
|
236
|
+
} ? OptAs extends FetchAs ? OptAs : ExtractAs<DropFirst<T>, Fallback> : ExtractAs<DropFirst<T>, Fallback>;
|
|
237
|
+
type ExtractFetchAs<T, TFallback = FetchAs.json> = T extends FetchAs ? T : T extends {
|
|
238
|
+
as: infer As;
|
|
239
|
+
} ? As extends FetchAs ? As : TFallback : TFallback;
|
|
240
|
+
type FetchArgs = [url: string | URL, options?: FetchOptions];
|
|
241
|
+
type FetchArgsInterceptor = [
|
|
242
|
+
url: string | URL,
|
|
243
|
+
options: FetchOptionsInterceptor
|
|
244
|
+
];
|
|
245
|
+
/** Custom fetch options (not used by built-in `fetch()`*/
|
|
246
|
+
type FetchCustomOptions = {
|
|
247
|
+
/**
|
|
248
|
+
* Specify how the parse the result. To get raw response use {@link FetchAs.response}.
|
|
249
|
+
* Default: 'json'
|
|
250
|
+
*/
|
|
251
|
+
as?: FetchAs;
|
|
252
|
+
/**
|
|
253
|
+
* An `AbortController` instance to control the request.
|
|
254
|
+
*
|
|
255
|
+
* If not provided, a new instance is automatically created internally.
|
|
256
|
+
*
|
|
257
|
+
* It is supported in addition to the standard `signal`. If both are provided, `abortCtrl` will be aborted
|
|
258
|
+
* when the `signal` aborts or when the request times out.
|
|
259
|
+
*
|
|
260
|
+
* Recommendation:
|
|
261
|
+
* - For request timeout purposes, setting a timeout duration will be sufficient.
|
|
262
|
+
* Abort controller/signal is not needed.
|
|
263
|
+
* - Use `abortCtrl` instead of `signal` to prevent creating internal `AbortController` instance.
|
|
264
|
+
*/
|
|
265
|
+
abortCtrl?: AbortController;
|
|
266
|
+
body?: PostBody | (() => PostBody);
|
|
267
|
+
/**
|
|
268
|
+
* Custom fetch function to use instead of the global `fetch`.
|
|
269
|
+
* Useful for testing or using a different fetch implementation (e.g. `node-fetch` in older Node versions).
|
|
270
|
+
*
|
|
271
|
+
* Default: `globalThis.fetch`
|
|
272
|
+
*/
|
|
273
|
+
fetchFunc?: FetchFunc;
|
|
274
|
+
errMsgs?: FetchErrMsgs;
|
|
275
|
+
/**
|
|
276
|
+
* Interceptor/transformer callback executed at different stages of the request.
|
|
277
|
+
* See {@link FetchInterceptors} for more details.
|
|
278
|
+
*/
|
|
279
|
+
interceptors?: FetchInterceptors;
|
|
280
|
+
/** Whether to validate URL before making the request. Default: `true` */
|
|
281
|
+
validateUrl?: boolean;
|
|
282
|
+
} & FetchRetryOptions & TimeoutOptions<[]>;
|
|
283
|
+
/** Default args */
|
|
284
|
+
type FetchDeferredArgs = [
|
|
285
|
+
url?: string | URL,
|
|
286
|
+
options?: Omit<FetchOptions, 'abortCtrl'>
|
|
287
|
+
];
|
|
288
|
+
type FetchErrMsgs = {
|
|
289
|
+
/** Error message to be used when request is aborted without specifying a message */
|
|
290
|
+
aborted?: string;
|
|
291
|
+
/** Error message to be use when URL validation fails */
|
|
292
|
+
invalidUrl?: string;
|
|
293
|
+
/** Error message to be used when request parse failes */
|
|
294
|
+
parseFailed?: string;
|
|
295
|
+
/** Error message to be used when request times out */
|
|
296
|
+
timedout?: string;
|
|
297
|
+
/** Error message to be used when request fails */
|
|
298
|
+
requestFailed?: string;
|
|
299
|
+
};
|
|
300
|
+
type FetchFunc = (...args: FetchArgs) => Promise<Response>;
|
|
301
|
+
/**
|
|
302
|
+
* Fetch request options
|
|
303
|
+
*/
|
|
304
|
+
type FetchOptions = Omit<RequestInit, 'body'> & FetchCustomOptions;
|
|
305
|
+
/** Default fetch options */
|
|
306
|
+
type FetchOptionsDefault = Omit<FetchOptionsInterceptor, 'abortCtrl' | 'as' | 'method' | 'signal' | 'timeout'> & {
|
|
307
|
+
/** Request timeout duration in milliseconds. Default: `30_000` (30 seconds) */
|
|
308
|
+
timeout: number;
|
|
309
|
+
};
|
|
310
|
+
/**
|
|
311
|
+
* Fetch options available to interceptors.
|
|
312
|
+
*
|
|
313
|
+
*/
|
|
314
|
+
type FetchOptionsInterceptor = Omit<FetchOptions, 'as' | 'errMsgs' | 'interceptors' | 'headers' | 'timeout' | keyof FetchRetryOptions> & {
|
|
315
|
+
as: FetchAs;
|
|
316
|
+
/** Error messages */
|
|
317
|
+
errMsgs: Required<FetchErrMsgs>;
|
|
318
|
+
headers: Headers;
|
|
319
|
+
/** Interceptors/transformers for fetch requests. See {@link FetchInterceptors} for more details. */
|
|
320
|
+
interceptors: FetchInterceptorsMerged;
|
|
321
|
+
timeout: number;
|
|
322
|
+
} & FetchRetryOptions;
|
|
323
|
+
/**
|
|
324
|
+
* Result types for specific parsers ("as": FetchAs)
|
|
325
|
+
*/
|
|
326
|
+
type FetchResult<T = unknown> = {
|
|
327
|
+
arrayBuffer: ArrayBuffer;
|
|
328
|
+
blob: Blob;
|
|
329
|
+
bytes: Uint8Array<ArrayBuffer>;
|
|
330
|
+
formData: FormData;
|
|
331
|
+
json: T;
|
|
332
|
+
text: string;
|
|
333
|
+
response: Response;
|
|
334
|
+
};
|
|
335
|
+
type GetFetchResult<As = unknown, T = never> = [T] extends [never] ? FetchResult[As extends unknown[] ? ExtractAs<As> : As extends FetchAs ? As : FetchAs.json] : T;
|
|
336
|
+
/**
|
|
337
|
+
* Fetch retry options
|
|
338
|
+
*/
|
|
339
|
+
type FetchRetryOptions = Omit<Partial<RetryOptions>, 'retry' | 'retryIf'> & {
|
|
340
|
+
/**
|
|
341
|
+
* Maximum number of retries.
|
|
342
|
+
*
|
|
343
|
+
* The total number of attempts will be `retry + 1`.
|
|
344
|
+
*
|
|
345
|
+
* Default: `0`
|
|
346
|
+
*/
|
|
347
|
+
retry?: number;
|
|
348
|
+
retryIf?: RetryIfFunc<Response>;
|
|
349
|
+
};
|
|
350
|
+
type PostBody = Record<string, unknown> | BodyInit | null;
|
|
351
|
+
type PostArgs = [
|
|
352
|
+
url: string | URL,
|
|
353
|
+
data?: PostBody | (() => PostBody),
|
|
354
|
+
options?: PostOptions
|
|
355
|
+
];
|
|
356
|
+
/**
|
|
357
|
+
* Dynamic arguments for deferred post-like methods.
|
|
358
|
+
*
|
|
359
|
+
* @example
|
|
360
|
+
* ```typescript
|
|
361
|
+
* import fetch, { type PostDeferredCbArgs } from '@superutils/fetch'
|
|
362
|
+
*
|
|
363
|
+
* // test with types
|
|
364
|
+
* type T1 = PostDeferredCbArgs<string | URL, undefined> // expected: [data, options]
|
|
365
|
+
* type T2 = PostDeferredCbArgs<undefined, string> // expected: [url, options]
|
|
366
|
+
* type T3 = PostDeferredCbArgs // expected: [url, data, options]
|
|
367
|
+
* type T4 = PostDeferredCbArgs<string, string> // expected: [options]
|
|
368
|
+
*
|
|
369
|
+
* const data = { name: 'test' }
|
|
370
|
+
* const url = 'https://domain.com'
|
|
371
|
+
* // test with fetch.post.deferred()
|
|
372
|
+
* const f1 = fetch.post.deferred({}, 'https://domain.com')
|
|
373
|
+
* // expected: [data, options]
|
|
374
|
+
* f1({data: 1}).then(console.log, console.warn)
|
|
375
|
+
*
|
|
376
|
+
* const f2 = fetch.post.deferred({}, undefined, 'dome data')
|
|
377
|
+
* // expected: [url, options]
|
|
378
|
+
* f2('https').then(console.log, console.warn)
|
|
379
|
+
*
|
|
380
|
+
* const f3 = fetch.post.deferred({})
|
|
381
|
+
* // expected: [url, data, options]
|
|
382
|
+
* f3('https://domain.com').then(console.log, console.warn)
|
|
383
|
+
*
|
|
384
|
+
* const f4 = fetch.post.deferred({}, 'url', 'data')
|
|
385
|
+
* // expected: [options]
|
|
386
|
+
* f4().then(console.log, console.warn)
|
|
387
|
+
* ```
|
|
388
|
+
*/
|
|
389
|
+
type PostDeferredCbArgs<DefaultUrl = undefined, DefaultData = undefined, Options = PostArgs[2], PostArgsReq extends unknown[] = Required<PostArgs>, _url = undefined extends DefaultUrl ? undefined : DefaultUrl, _data = undefined extends DefaultData ? undefined : DefaultData> = [_url, _data] extends [PostArgsReq[0], undefined] ? [
|
|
390
|
+
data?: PostArgs[1],
|
|
391
|
+
options?: PostArgs[2]
|
|
392
|
+
] : [
|
|
393
|
+
_url,
|
|
394
|
+
_data
|
|
395
|
+
] extends [undefined, PostArgsReq[1]] ? [url: PostArgs[0], options?: PostArgs[2]] : [
|
|
396
|
+
_url,
|
|
397
|
+
_data
|
|
398
|
+
] extends [PostArgsReq[0], PostArgsReq[1]] ? [options?: PostArgs[2]] : [url: PostArgs[0], data?: PostArgs[1], options?: Options];
|
|
399
|
+
/** Request options for POST-like methods that allow "options.body" */
|
|
400
|
+
type PostOptions = {
|
|
401
|
+
/** Default: `'post'` */
|
|
402
|
+
method?: 'post' | 'put' | 'patch' | 'delete' | 'POST' | 'PUT' | 'PATCH' | 'DELETE';
|
|
403
|
+
} & Omit<FetchOptions, 'method'>;
|
|
404
|
+
|
|
405
|
+
/** Custom error message for fetch requests with more detailed info about the request URL, fetch options and response */
|
|
406
|
+
declare class FetchError extends Error {
|
|
407
|
+
/** Create a new `FetchError` with a new `message` while preserving all metadata */
|
|
408
|
+
clone: (newMessage: string) => FetchError;
|
|
409
|
+
options: FetchOptions;
|
|
410
|
+
response: Response | undefined;
|
|
411
|
+
url: string | URL;
|
|
412
|
+
constructor(message: string, options: {
|
|
413
|
+
cause?: unknown;
|
|
414
|
+
options: FetchOptions;
|
|
415
|
+
response?: Response;
|
|
416
|
+
url: string | URL;
|
|
417
|
+
});
|
|
418
|
+
}
|
|
419
|
+
|
|
420
|
+
type IPromise_Fetch<T = unknown> = Omit<IPromisE_Timeout<T>, 'abortCtrl'> & {
|
|
421
|
+
/** An `AbortController` instance to control the request. */
|
|
422
|
+
abortCtrl: AbortController;
|
|
423
|
+
};
|
|
424
|
+
|
|
425
|
+
/**
|
|
426
|
+
* Defines client generic parameter T based on fixed options.
|
|
427
|
+
*
|
|
428
|
+
* If `fixedOptions.as` is defined and not `FetcAs.json`, then `T` will be `never`.
|
|
429
|
+
*/
|
|
430
|
+
type ClientData<FixedOptions> = ExtractAs<[FixedOptions]> extends FetchAs.json ? unknown : never;
|
|
431
|
+
/**
|
|
432
|
+
* Create a reusable fetch client with shared options. The returned function comes attached with a
|
|
433
|
+
* `.deferred()` function for debounce and throttle behavior.
|
|
434
|
+
*
|
|
435
|
+
* The `createClient` utility streamlines the creation of dedicated API clients by generating pre-configured fetch
|
|
436
|
+
* functions. These functions can be equipped with default options like headers, timeouts, or a specific HTTP method,
|
|
437
|
+
* which minimizes code repetition across your application. If a method is not specified during creation, the client
|
|
438
|
+
* will default to `GET`.
|
|
439
|
+
*
|
|
440
|
+
* The returned client also includes a `.deferred()` method, providing the same debounce, throttle, and sequential
|
|
441
|
+
* execution capabilities found in functions like `fetch.get.deferred()`.
|
|
442
|
+
*
|
|
443
|
+
* @example create reusable clients
|
|
444
|
+
* ```javascript
|
|
445
|
+
* import { createClient } from '@superutils/fetch'
|
|
446
|
+
*
|
|
447
|
+
* // Create a "GET" client with default headers and a 5-second timeout
|
|
448
|
+
* const apiClient = createClient(
|
|
449
|
+
* {
|
|
450
|
+
* // fixed options cannot be overridden
|
|
451
|
+
* method: 'get',
|
|
452
|
+
* },
|
|
453
|
+
* {
|
|
454
|
+
* // default options can be overridden
|
|
455
|
+
* headers: {
|
|
456
|
+
* Authorization: 'Bearer my-secret-token',
|
|
457
|
+
* 'Content-Type': 'application/json',
|
|
458
|
+
* },
|
|
459
|
+
* timeout: 5000,
|
|
460
|
+
* },
|
|
461
|
+
* {
|
|
462
|
+
* // default defer options (can be overridden)
|
|
463
|
+
* delay: 300,
|
|
464
|
+
* retry: 2, // If request fails, retry up to two more times
|
|
465
|
+
* },
|
|
466
|
+
* )
|
|
467
|
+
*
|
|
468
|
+
* // Use it just like the standard fetch
|
|
469
|
+
* apiClient('https://dummyjson.com/products/1', {
|
|
470
|
+
* // The 'method' property cannot be overridden as it is used in the fixed options when creating the client.
|
|
471
|
+
* // In TypeScript, the compiler will not allow this property.
|
|
472
|
+
* // In Javascript, it will simply be ignored.
|
|
473
|
+
* // method: 'post',
|
|
474
|
+
* timeout: 3000, // The 'timeout' property can be overridden
|
|
475
|
+
* }).then(console.log, console.warn)
|
|
476
|
+
*
|
|
477
|
+
* // create a deferred client using "apiClient"
|
|
478
|
+
* const deferredClient = apiClient.deferred(
|
|
479
|
+
* { retry: 0 }, // disable retrying by overriding the `retry` defer option
|
|
480
|
+
* 'https://dummyjson.com/products/1',
|
|
481
|
+
* { timeout: 3000 },
|
|
482
|
+
* )
|
|
483
|
+
* deferredClient({ timeout: 10000 }) // timeout is overridden by individual request
|
|
484
|
+
* .then(console.log, console.warn)
|
|
485
|
+
* ```
|
|
486
|
+
*/
|
|
487
|
+
declare const createClient: <FixedOptions extends FetchOptions | undefined, CommonOptions extends ExcludeOptions<FixedOptions> | undefined, CommonDelay extends number>(
|
|
488
|
+
/** Mandatory fetch options that cannot be overriden by individual request */
|
|
489
|
+
fixedOptions?: FixedOptions,
|
|
490
|
+
/** Common fetch options that can be overriden by individual request */
|
|
491
|
+
commonOptions?: FetchOptions & CommonOptions, commonDeferOptions?: DeferredAsyncOptions<unknown, CommonDelay>) => {
|
|
492
|
+
<T extends ClientData<FixedOptions> = never, TOptions extends ExcludeOptions<FixedOptions> | undefined = ExcludeOptions<FixedOptions> | undefined, Result = GetFetchResult<[FixedOptions, TOptions, CommonOptions], T>>(url: FetchArgs[0], options?: TOptions): IPromise_Fetch<Result>;
|
|
493
|
+
deferred<ThisArg, Delay extends CommonDelay | number, DefaultUrl extends FetchArgs[0] | undefined = string | URL | undefined, DefaultOptions extends ExcludeOptions<FixedOptions> | undefined = ExcludeOptions<FixedOptions> | undefined>(deferOptions?: DeferredAsyncOptions<ThisArg, Delay>, defaultUrl?: DefaultUrl, defaultOptions?: DefaultOptions): <T extends ClientData<FixedOptions> = never, TOptions_1 extends ExcludeOptions<FixedOptions> | undefined = ExcludeOptions<FixedOptions> | undefined, Result_1 = GetFetchResult<[FixedOptions, TOptions_1, DefaultOptions, CommonOptions], T>>(...args: DefaultUrl extends undefined ? [url: FetchArgs[0], options?: TOptions_1] : [options?: TOptions_1]) => IPromise_Fetch<Result_1>;
|
|
494
|
+
};
|
|
495
|
+
|
|
496
|
+
/**
|
|
497
|
+
* Create a reusable fetch client with shared options. The returned function comes attached with a
|
|
498
|
+
* `.deferred()` function for debounced and throttled request.
|
|
499
|
+
* While `createClient()` is versatile enough for any HTTP method, `createPostClient()` is specifically designed for
|
|
500
|
+
* methods that require a request body, such as `DELETE`, `PATCH`, `POST`, and `PUT`. If a method is not provided, it
|
|
501
|
+
* defaults to `POST`. The generated client accepts an additional second parameter (`data`) for the request payload.
|
|
502
|
+
*
|
|
503
|
+
* Similar to `createClient`, the returned function comes equipped with a `.deferred()` method, enabling debounced,
|
|
504
|
+
* throttled, or sequential execution.
|
|
505
|
+
*
|
|
506
|
+
* @example create reusable clients
|
|
507
|
+
* ```javascript
|
|
508
|
+
* import { createPostClient, FetchAs } from '@superutils/fetch'
|
|
509
|
+
*
|
|
510
|
+
* // Create a POST client with 10-second as the default timeout
|
|
511
|
+
* const postClient = createPostClient(
|
|
512
|
+
* {
|
|
513
|
+
* method: 'post',
|
|
514
|
+
* headers: { 'content-type': 'application/json' },
|
|
515
|
+
* },
|
|
516
|
+
* { timeout: 10000 },
|
|
517
|
+
* )
|
|
518
|
+
*
|
|
519
|
+
* // Invoking `postClient()` automatically applies the pre-configured options
|
|
520
|
+
* postClient(
|
|
521
|
+
* 'https://dummyjson.com/products/add',
|
|
522
|
+
* { title: 'New Product' }, // data/body
|
|
523
|
+
* {}, // other options
|
|
524
|
+
* ).then(console.log)
|
|
525
|
+
*
|
|
526
|
+
* // create a deferred client using "postClient"
|
|
527
|
+
* const updateProduct = postClient.deferred(
|
|
528
|
+
* {
|
|
529
|
+
* delay: 300, // debounce duration
|
|
530
|
+
* onResult: console.log, // prints only successful results
|
|
531
|
+
* },
|
|
532
|
+
* 'https://dummyjson.com/products/add',
|
|
533
|
+
* {
|
|
534
|
+
* method: 'patch',
|
|
535
|
+
* timeout: 3000,
|
|
536
|
+
* },
|
|
537
|
+
* )
|
|
538
|
+
* updateProduct({ title: 'New title 1' }) // ignored by debounce
|
|
539
|
+
* updateProduct({ title: 'New title 2' }) // executed
|
|
540
|
+
* ```
|
|
541
|
+
*/
|
|
542
|
+
declare const createPostClient: <FixedOptions extends PostOptions | undefined, CommonOptions extends ExcludePostOptions<FixedOptions> | undefined, CommonDelay extends number = number>(
|
|
543
|
+
/** Mandatory fetch options that cannot be overriden by individual request */
|
|
544
|
+
fixedOptions?: FixedOptions,
|
|
545
|
+
/** Common fetch options that can be overriden by individual request */
|
|
546
|
+
commonOptions?: PostOptions & CommonOptions, commonDeferOptions?: DeferredAsyncOptions<unknown, CommonDelay>) => {
|
|
547
|
+
<T extends ClientData<FixedOptions> = never, Options extends ExcludePostOptions<FixedOptions> | undefined = ExcludePostOptions<FixedOptions> | undefined, Result = GetFetchResult<[FixedOptions, Options, CommonOptions], T>>(url: PostArgs[0], data?: PostArgs[1], options?: Options): IPromise_Fetch<Result>;
|
|
548
|
+
deferred<ThisArg, DefaultUrl extends PostArgs[0] | undefined, DefaultData extends PostArgs[1] | undefined, DefaultOptions extends ExcludePostOptions<FixedOptions> | undefined = ExcludePostOptions<FixedOptions> | undefined, Delay extends CommonDelay | number = number>(deferOptions?: DeferredAsyncOptions<ThisArg, Delay>, defaultUrl?: DefaultUrl, defaultData?: DefaultData, defaultOptions?: DefaultOptions): <T extends ClientData<FixedOptions> = never, Options_1 extends ExcludePostOptions<FixedOptions> | undefined = ExcludePostOptions<FixedOptions> | undefined, TReturn = GetFetchResult<[FixedOptions, Options_1, DefaultOptions, CommonOptions], T>>(...args: PostDeferredCbArgs<DefaultUrl, DefaultData, Options_1>) => IPromise_Fetch<TReturn>;
|
|
549
|
+
};
|
|
550
|
+
|
|
551
|
+
/**
|
|
552
|
+
* Gracefully executes interceptors and returns the processed value.
|
|
553
|
+
* If the value is not transformed (by returning a new value) by the interceptors,
|
|
554
|
+
* the original value is returned.
|
|
555
|
+
*
|
|
556
|
+
* @param value value to be passed to the interceptors
|
|
557
|
+
* @param signal The AbortController used to monitor the request status. If the signal is aborted (e.g. due to
|
|
558
|
+
* timeout or manual cancellation), the interceptor chain halts immediately. Note: This does not interrupt the
|
|
559
|
+
* currently executing interceptor, but prevents subsequent ones from running.
|
|
560
|
+
* @param interceptors interceptor/transformer callbacks
|
|
561
|
+
* @param args (optional) common arguments to be supplied to all the interceptors in addition to
|
|
562
|
+
* the `value' which will always be the first argument.
|
|
563
|
+
*
|
|
564
|
+
* Interceptor arguments: `[value, ...args]`
|
|
565
|
+
*/
|
|
566
|
+
declare const executeInterceptors: <T, TArgs extends unknown[]>(value: T, signal?: AbortSignal, interceptors?: Interceptor<T, TArgs>[], ...args: TArgs) => Promise<T>;
|
|
567
|
+
|
|
568
|
+
/**
|
|
569
|
+
* Extended `fetch` with timeout, retry, and other options. Automatically parses as JSON by default on success.
|
|
570
|
+
*
|
|
571
|
+
* @param url request URL
|
|
572
|
+
* @param options (optional) Standard `fetch` options extended with {@link FetchCustomOptions}.
|
|
573
|
+
* Default "content-type" header is 'application/json'.
|
|
574
|
+
* @param options.as (optional) determines how to parse the result. Default: {@link FetchAs.json}
|
|
575
|
+
* @param options.method (optional) fetch method. Default: `'get'`
|
|
576
|
+
*
|
|
577
|
+
* @example Make a simple HTTP requests
|
|
578
|
+
* ```typescript
|
|
579
|
+
* import { fetch } from '@superutils/fetch'
|
|
580
|
+
*
|
|
581
|
+
* // no need for `response.json()` or `result.data.data` drilling
|
|
582
|
+
* fetch('https://dummyjson.com/products/1')
|
|
583
|
+
* .then(product => console.log(product))
|
|
584
|
+
* ```
|
|
585
|
+
*/
|
|
586
|
+
declare const fetch$1: {
|
|
587
|
+
<T = unknown, TOptions extends FetchOptions = FetchOptions, TAs extends FetchAs = TOptions["as"] extends FetchAs ? TOptions["as"] : FetchAs.response, TReturn = FetchResult<T>[TAs]>(url: string | URL, options?: FetchOptions & TOptions): IPromise_Fetch<TReturn>;
|
|
588
|
+
/** Default fetch options */
|
|
589
|
+
defaults: FetchOptionsDefault;
|
|
590
|
+
};
|
|
591
|
+
|
|
592
|
+
/**
|
|
593
|
+
* Merge one or more {@link FetchOptions}
|
|
594
|
+
*
|
|
595
|
+
* Notes:
|
|
596
|
+
* - item properties will be prioritized in the order of sequence they were passed in
|
|
597
|
+
* - the following properties will be merged
|
|
598
|
+
* * `errMsgs`
|
|
599
|
+
* * `headers`
|
|
600
|
+
* * `interceptors`
|
|
601
|
+
* - all other properties will simply override previous values
|
|
602
|
+
*
|
|
603
|
+
* @returns combined
|
|
604
|
+
*/
|
|
605
|
+
declare const mergeOptions: (...allOptions: (FetchOptions | undefined)[]) => FetchOptionsInterceptor;
|
|
606
|
+
|
|
607
|
+
declare const methods: {
|
|
608
|
+
/** Make HTTP requests with method GET */
|
|
609
|
+
get: {
|
|
610
|
+
<T extends unknown = never, TOptions extends ({
|
|
611
|
+
headers?: HeadersInit | undefined;
|
|
612
|
+
} & Omit<FetchOptions, "headers" | "method"> & Partial<Record<"method", never>>) | undefined = ({
|
|
613
|
+
headers?: HeadersInit | undefined;
|
|
614
|
+
} & Omit<FetchOptions, "headers" | "method"> & Partial<Record<"method", never>>) | undefined, Result = GetFetchResult<[{
|
|
615
|
+
method: string;
|
|
616
|
+
}, TOptions, ({
|
|
617
|
+
headers?: HeadersInit | undefined;
|
|
618
|
+
} & Omit<FetchOptions, "headers" | "method"> & Partial<Record<"method", never>>) | undefined], T>>(url: FetchArgs[0], options?: TOptions | undefined): IPromise_Fetch<Result>;
|
|
619
|
+
deferred<ThisArg, Delay extends number, DefaultUrl extends FetchArgs[0] | undefined = string | URL | undefined, DefaultOptions extends ({
|
|
620
|
+
headers?: HeadersInit | undefined;
|
|
621
|
+
} & Omit<FetchOptions, "headers" | "method"> & Partial<Record<"method", never>>) | undefined = ({
|
|
622
|
+
headers?: HeadersInit | undefined;
|
|
623
|
+
} & Omit<FetchOptions, "headers" | "method"> & Partial<Record<"method", never>>) | undefined>(deferOptions?: _superutils_promise.DeferredAsyncOptions<ThisArg, Delay> | undefined, defaultUrl?: DefaultUrl | undefined, defaultOptions?: DefaultOptions | undefined): <T extends unknown = never, TOptions extends ({
|
|
624
|
+
headers?: HeadersInit | undefined;
|
|
625
|
+
} & Omit<FetchOptions, "headers" | "method"> & Partial<Record<"method", never>>) | undefined = ({
|
|
626
|
+
headers?: HeadersInit | undefined;
|
|
627
|
+
} & Omit<FetchOptions, "headers" | "method"> & Partial<Record<"method", never>>) | undefined, Result = GetFetchResult<[{
|
|
628
|
+
method: string;
|
|
629
|
+
}, TOptions, DefaultOptions, ({
|
|
630
|
+
headers?: HeadersInit | undefined;
|
|
631
|
+
} & Omit<FetchOptions, "headers" | "method"> & Partial<Record<"method", never>>) | undefined], T>>(...args: DefaultUrl extends undefined ? [url: string | URL, options?: TOptions | undefined] : [options?: TOptions | undefined]) => IPromise_Fetch<Result>;
|
|
632
|
+
};
|
|
633
|
+
/** Make HTTP requests with method HEAD */
|
|
634
|
+
head: {
|
|
635
|
+
<T extends unknown = never, TOptions extends ({
|
|
636
|
+
headers?: HeadersInit | undefined;
|
|
637
|
+
} & Omit<FetchOptions, "headers" | "method"> & Partial<Record<"method", never>>) | undefined = ({
|
|
638
|
+
headers?: HeadersInit | undefined;
|
|
639
|
+
} & Omit<FetchOptions, "headers" | "method"> & Partial<Record<"method", never>>) | undefined, Result = GetFetchResult<[{
|
|
640
|
+
method: string;
|
|
641
|
+
}, TOptions, ({
|
|
642
|
+
headers?: HeadersInit | undefined;
|
|
643
|
+
} & Omit<FetchOptions, "headers" | "method"> & Partial<Record<"method", never>>) | undefined], T>>(url: FetchArgs[0], options?: TOptions | undefined): IPromise_Fetch<Result>;
|
|
644
|
+
deferred<ThisArg, Delay extends number, DefaultUrl extends FetchArgs[0] | undefined = string | URL | undefined, DefaultOptions extends ({
|
|
645
|
+
headers?: HeadersInit | undefined;
|
|
646
|
+
} & Omit<FetchOptions, "headers" | "method"> & Partial<Record<"method", never>>) | undefined = ({
|
|
647
|
+
headers?: HeadersInit | undefined;
|
|
648
|
+
} & Omit<FetchOptions, "headers" | "method"> & Partial<Record<"method", never>>) | undefined>(deferOptions?: _superutils_promise.DeferredAsyncOptions<ThisArg, Delay> | undefined, defaultUrl?: DefaultUrl | undefined, defaultOptions?: DefaultOptions | undefined): <T extends unknown = never, TOptions extends ({
|
|
649
|
+
headers?: HeadersInit | undefined;
|
|
650
|
+
} & Omit<FetchOptions, "headers" | "method"> & Partial<Record<"method", never>>) | undefined = ({
|
|
651
|
+
headers?: HeadersInit | undefined;
|
|
652
|
+
} & Omit<FetchOptions, "headers" | "method"> & Partial<Record<"method", never>>) | undefined, Result = GetFetchResult<[{
|
|
653
|
+
method: string;
|
|
654
|
+
}, TOptions, DefaultOptions, ({
|
|
655
|
+
headers?: HeadersInit | undefined;
|
|
656
|
+
} & Omit<FetchOptions, "headers" | "method"> & Partial<Record<"method", never>>) | undefined], T>>(...args: DefaultUrl extends undefined ? [url: string | URL, options?: TOptions | undefined] : [options?: TOptions | undefined]) => IPromise_Fetch<Result>;
|
|
657
|
+
};
|
|
658
|
+
/** Make HTTP requests with method OPTIONS */
|
|
659
|
+
options: {
|
|
660
|
+
<T extends unknown = never, TOptions extends ({
|
|
661
|
+
headers?: HeadersInit | undefined;
|
|
662
|
+
} & Omit<FetchOptions, "headers" | "method"> & Partial<Record<"method", never>>) | undefined = ({
|
|
663
|
+
headers?: HeadersInit | undefined;
|
|
664
|
+
} & Omit<FetchOptions, "headers" | "method"> & Partial<Record<"method", never>>) | undefined, Result = GetFetchResult<[{
|
|
665
|
+
method: string;
|
|
666
|
+
}, TOptions, ({
|
|
667
|
+
headers?: HeadersInit | undefined;
|
|
668
|
+
} & Omit<FetchOptions, "headers" | "method"> & Partial<Record<"method", never>>) | undefined], T>>(url: FetchArgs[0], options?: TOptions | undefined): IPromise_Fetch<Result>;
|
|
669
|
+
deferred<ThisArg, Delay extends number, DefaultUrl extends FetchArgs[0] | undefined = string | URL | undefined, DefaultOptions extends ({
|
|
670
|
+
headers?: HeadersInit | undefined;
|
|
671
|
+
} & Omit<FetchOptions, "headers" | "method"> & Partial<Record<"method", never>>) | undefined = ({
|
|
672
|
+
headers?: HeadersInit | undefined;
|
|
673
|
+
} & Omit<FetchOptions, "headers" | "method"> & Partial<Record<"method", never>>) | undefined>(deferOptions?: _superutils_promise.DeferredAsyncOptions<ThisArg, Delay> | undefined, defaultUrl?: DefaultUrl | undefined, defaultOptions?: DefaultOptions | undefined): <T extends unknown = never, TOptions extends ({
|
|
674
|
+
headers?: HeadersInit | undefined;
|
|
675
|
+
} & Omit<FetchOptions, "headers" | "method"> & Partial<Record<"method", never>>) | undefined = ({
|
|
676
|
+
headers?: HeadersInit | undefined;
|
|
677
|
+
} & Omit<FetchOptions, "headers" | "method"> & Partial<Record<"method", never>>) | undefined, Result = GetFetchResult<[{
|
|
678
|
+
method: string;
|
|
679
|
+
}, TOptions, DefaultOptions, ({
|
|
680
|
+
headers?: HeadersInit | undefined;
|
|
681
|
+
} & Omit<FetchOptions, "headers" | "method"> & Partial<Record<"method", never>>) | undefined], T>>(...args: DefaultUrl extends undefined ? [url: string | URL, options?: TOptions | undefined] : [options?: TOptions | undefined]) => IPromise_Fetch<Result>;
|
|
682
|
+
};
|
|
683
|
+
/** Make HTTP requests with method DELETE */
|
|
684
|
+
delete: {
|
|
685
|
+
<T extends unknown = never, Options extends ({
|
|
686
|
+
headers?: HeadersInit | undefined;
|
|
687
|
+
} & Omit<PostOptions, "headers" | "method"> & Partial<Record<"method", never>>) | undefined = ({
|
|
688
|
+
headers?: HeadersInit | undefined;
|
|
689
|
+
} & Omit<PostOptions, "headers" | "method"> & Partial<Record<"method", never>>) | undefined, Result = GetFetchResult<[{
|
|
690
|
+
method: "delete";
|
|
691
|
+
}, Options, ({
|
|
692
|
+
headers?: HeadersInit | undefined;
|
|
693
|
+
} & Omit<PostOptions, "headers" | "method"> & Partial<Record<"method", never>>) | undefined], T>>(url: PostArgs[0], data?: PostArgs[1], options?: Options | undefined): IPromise_Fetch<Result>;
|
|
694
|
+
deferred<ThisArg, DefaultUrl extends PostArgs[0] | undefined, DefaultData extends PostArgs[1] | undefined, DefaultOptions extends ({
|
|
695
|
+
headers?: HeadersInit | undefined;
|
|
696
|
+
} & Omit<PostOptions, "headers" | "method"> & Partial<Record<"method", never>>) | undefined = ({
|
|
697
|
+
headers?: HeadersInit | undefined;
|
|
698
|
+
} & Omit<PostOptions, "headers" | "method"> & Partial<Record<"method", never>>) | undefined, Delay extends number = number>(deferOptions?: _superutils_promise.DeferredAsyncOptions<ThisArg, Delay> | undefined, defaultUrl?: DefaultUrl | undefined, defaultData?: DefaultData | undefined, defaultOptions?: DefaultOptions | undefined): <T extends unknown = never, Options extends ({
|
|
699
|
+
headers?: HeadersInit | undefined;
|
|
700
|
+
} & Omit<PostOptions, "headers" | "method"> & Partial<Record<"method", never>>) | undefined = ({
|
|
701
|
+
headers?: HeadersInit | undefined;
|
|
702
|
+
} & Omit<PostOptions, "headers" | "method"> & Partial<Record<"method", never>>) | undefined, TReturn = GetFetchResult<[{
|
|
703
|
+
method: "delete";
|
|
704
|
+
}, Options, DefaultOptions, ({
|
|
705
|
+
headers?: HeadersInit | undefined;
|
|
706
|
+
} & Omit<PostOptions, "headers" | "method"> & Partial<Record<"method", never>>) | undefined], T>>(...args: PostDeferredCbArgs<DefaultUrl, DefaultData, Options, [url: string | URL, data: PostBody | (() => PostBody), options: PostOptions], undefined extends DefaultUrl ? DefaultUrl & undefined : DefaultUrl, undefined extends DefaultData ? DefaultData & undefined : DefaultData>) => IPromise_Fetch<TReturn>;
|
|
707
|
+
};
|
|
708
|
+
/** Make HTTP requests with method PATCH */
|
|
709
|
+
patch: {
|
|
710
|
+
<T extends unknown = never, Options extends ({
|
|
711
|
+
headers?: HeadersInit | undefined;
|
|
712
|
+
} & Omit<PostOptions, "headers" | "method"> & Partial<Record<"method", never>>) | undefined = ({
|
|
713
|
+
headers?: HeadersInit | undefined;
|
|
714
|
+
} & Omit<PostOptions, "headers" | "method"> & Partial<Record<"method", never>>) | undefined, Result = GetFetchResult<[{
|
|
715
|
+
method: "patch";
|
|
716
|
+
}, Options, ({
|
|
717
|
+
headers?: HeadersInit | undefined;
|
|
718
|
+
} & Omit<PostOptions, "headers" | "method"> & Partial<Record<"method", never>>) | undefined], T>>(url: PostArgs[0], data?: PostArgs[1], options?: Options | undefined): IPromise_Fetch<Result>;
|
|
719
|
+
deferred<ThisArg, DefaultUrl extends PostArgs[0] | undefined, DefaultData extends PostArgs[1] | undefined, DefaultOptions extends ({
|
|
720
|
+
headers?: HeadersInit | undefined;
|
|
721
|
+
} & Omit<PostOptions, "headers" | "method"> & Partial<Record<"method", never>>) | undefined = ({
|
|
722
|
+
headers?: HeadersInit | undefined;
|
|
723
|
+
} & Omit<PostOptions, "headers" | "method"> & Partial<Record<"method", never>>) | undefined, Delay extends number = number>(deferOptions?: _superutils_promise.DeferredAsyncOptions<ThisArg, Delay> | undefined, defaultUrl?: DefaultUrl | undefined, defaultData?: DefaultData | undefined, defaultOptions?: DefaultOptions | undefined): <T extends unknown = never, Options extends ({
|
|
724
|
+
headers?: HeadersInit | undefined;
|
|
725
|
+
} & Omit<PostOptions, "headers" | "method"> & Partial<Record<"method", never>>) | undefined = ({
|
|
726
|
+
headers?: HeadersInit | undefined;
|
|
727
|
+
} & Omit<PostOptions, "headers" | "method"> & Partial<Record<"method", never>>) | undefined, TReturn = GetFetchResult<[{
|
|
728
|
+
method: "patch";
|
|
729
|
+
}, Options, DefaultOptions, ({
|
|
730
|
+
headers?: HeadersInit | undefined;
|
|
731
|
+
} & Omit<PostOptions, "headers" | "method"> & Partial<Record<"method", never>>) | undefined], T>>(...args: PostDeferredCbArgs<DefaultUrl, DefaultData, Options, [url: string | URL, data: PostBody | (() => PostBody), options: PostOptions], undefined extends DefaultUrl ? DefaultUrl & undefined : DefaultUrl, undefined extends DefaultData ? DefaultData & undefined : DefaultData>) => IPromise_Fetch<TReturn>;
|
|
732
|
+
};
|
|
733
|
+
/** Make HTTP requests with method POST */
|
|
734
|
+
post: {
|
|
735
|
+
<T extends unknown = never, Options extends ({
|
|
736
|
+
headers?: HeadersInit | undefined;
|
|
737
|
+
} & Omit<PostOptions, "headers" | "method"> & Partial<Record<"method", never>>) | undefined = ({
|
|
738
|
+
headers?: HeadersInit | undefined;
|
|
739
|
+
} & Omit<PostOptions, "headers" | "method"> & Partial<Record<"method", never>>) | undefined, Result = GetFetchResult<[{
|
|
740
|
+
method: "post";
|
|
741
|
+
}, Options, ({
|
|
742
|
+
headers?: HeadersInit | undefined;
|
|
743
|
+
} & Omit<PostOptions, "headers" | "method"> & Partial<Record<"method", never>>) | undefined], T>>(url: PostArgs[0], data?: PostArgs[1], options?: Options | undefined): IPromise_Fetch<Result>;
|
|
744
|
+
deferred<ThisArg, DefaultUrl extends PostArgs[0] | undefined, DefaultData extends PostArgs[1] | undefined, DefaultOptions extends ({
|
|
745
|
+
headers?: HeadersInit | undefined;
|
|
746
|
+
} & Omit<PostOptions, "headers" | "method"> & Partial<Record<"method", never>>) | undefined = ({
|
|
747
|
+
headers?: HeadersInit | undefined;
|
|
748
|
+
} & Omit<PostOptions, "headers" | "method"> & Partial<Record<"method", never>>) | undefined, Delay extends number = number>(deferOptions?: _superutils_promise.DeferredAsyncOptions<ThisArg, Delay> | undefined, defaultUrl?: DefaultUrl | undefined, defaultData?: DefaultData | undefined, defaultOptions?: DefaultOptions | undefined): <T extends unknown = never, Options extends ({
|
|
749
|
+
headers?: HeadersInit | undefined;
|
|
750
|
+
} & Omit<PostOptions, "headers" | "method"> & Partial<Record<"method", never>>) | undefined = ({
|
|
751
|
+
headers?: HeadersInit | undefined;
|
|
752
|
+
} & Omit<PostOptions, "headers" | "method"> & Partial<Record<"method", never>>) | undefined, TReturn = GetFetchResult<[{
|
|
753
|
+
method: "post";
|
|
754
|
+
}, Options, DefaultOptions, ({
|
|
755
|
+
headers?: HeadersInit | undefined;
|
|
756
|
+
} & Omit<PostOptions, "headers" | "method"> & Partial<Record<"method", never>>) | undefined], T>>(...args: PostDeferredCbArgs<DefaultUrl, DefaultData, Options, [url: string | URL, data: PostBody | (() => PostBody), options: PostOptions], undefined extends DefaultUrl ? DefaultUrl & undefined : DefaultUrl, undefined extends DefaultData ? DefaultData & undefined : DefaultData>) => IPromise_Fetch<TReturn>;
|
|
757
|
+
};
|
|
758
|
+
/** Make HTTP requests with method PUT */
|
|
759
|
+
put: {
|
|
760
|
+
<T extends unknown = never, Options extends ({
|
|
761
|
+
headers?: HeadersInit | undefined;
|
|
762
|
+
} & Omit<PostOptions, "headers" | "method"> & Partial<Record<"method", never>>) | undefined = ({
|
|
763
|
+
headers?: HeadersInit | undefined;
|
|
764
|
+
} & Omit<PostOptions, "headers" | "method"> & Partial<Record<"method", never>>) | undefined, Result = GetFetchResult<[{
|
|
765
|
+
method: "put";
|
|
766
|
+
}, Options, ({
|
|
767
|
+
headers?: HeadersInit | undefined;
|
|
768
|
+
} & Omit<PostOptions, "headers" | "method"> & Partial<Record<"method", never>>) | undefined], T>>(url: PostArgs[0], data?: PostArgs[1], options?: Options | undefined): IPromise_Fetch<Result>;
|
|
769
|
+
deferred<ThisArg, DefaultUrl extends PostArgs[0] | undefined, DefaultData extends PostArgs[1] | undefined, DefaultOptions extends ({
|
|
770
|
+
headers?: HeadersInit | undefined;
|
|
771
|
+
} & Omit<PostOptions, "headers" | "method"> & Partial<Record<"method", never>>) | undefined = ({
|
|
772
|
+
headers?: HeadersInit | undefined;
|
|
773
|
+
} & Omit<PostOptions, "headers" | "method"> & Partial<Record<"method", never>>) | undefined, Delay extends number = number>(deferOptions?: _superutils_promise.DeferredAsyncOptions<ThisArg, Delay> | undefined, defaultUrl?: DefaultUrl | undefined, defaultData?: DefaultData | undefined, defaultOptions?: DefaultOptions | undefined): <T extends unknown = never, Options extends ({
|
|
774
|
+
headers?: HeadersInit | undefined;
|
|
775
|
+
} & Omit<PostOptions, "headers" | "method"> & Partial<Record<"method", never>>) | undefined = ({
|
|
776
|
+
headers?: HeadersInit | undefined;
|
|
777
|
+
} & Omit<PostOptions, "headers" | "method"> & Partial<Record<"method", never>>) | undefined, TReturn = GetFetchResult<[{
|
|
778
|
+
method: "put";
|
|
779
|
+
}, Options, DefaultOptions, ({
|
|
780
|
+
headers?: HeadersInit | undefined;
|
|
781
|
+
} & Omit<PostOptions, "headers" | "method"> & Partial<Record<"method", never>>) | undefined], T>>(...args: PostDeferredCbArgs<DefaultUrl, DefaultData, Options, [url: string | URL, data: PostBody | (() => PostBody), options: PostOptions], undefined extends DefaultUrl ? DefaultUrl & undefined : DefaultUrl, undefined extends DefaultData ? DefaultData & undefined : DefaultData>) => IPromise_Fetch<TReturn>;
|
|
782
|
+
};
|
|
783
|
+
};
|
|
784
|
+
/**
|
|
785
|
+
* A `fetch()` replacement that simplifies data fetching with automatic JSON parsing, request timeouts, retries,
|
|
786
|
+
* and handy interceptors that also work as transformers. It also includes deferred and throttled request
|
|
787
|
+
* capabilities for complex asynchronous control flows.
|
|
788
|
+
*
|
|
789
|
+
* Will reject promise if response status code is not 2xx (200 <= status < 300).
|
|
790
|
+
*
|
|
791
|
+
* ## Method Specific Functions
|
|
792
|
+
*
|
|
793
|
+
* While `fetch()` provides access to all HTTP request methods by specifying it in options (eg: `{ method: 'get' }`),
|
|
794
|
+
* for ease of use you can also use the following:
|
|
795
|
+
*
|
|
796
|
+
* - `fetch.delete(...)`
|
|
797
|
+
* - `fetch.get(...)`
|
|
798
|
+
* - `fetch.head(...)`
|
|
799
|
+
* - `fetch.options(...)`
|
|
800
|
+
* - `fetch.patch(...)`
|
|
801
|
+
* - `fetch.post(...)`
|
|
802
|
+
* - `fetch.put(...)`
|
|
803
|
+
*
|
|
804
|
+
* **Deferred variants:** To debounce/throttle requests.
|
|
805
|
+
*
|
|
806
|
+
* - `fetch.delete.deferred(...)`
|
|
807
|
+
* - `fetch.get.deferred(...)`
|
|
808
|
+
* - `fetch.head.deferred(...)`
|
|
809
|
+
* - `fetch.options.deferred(...)`
|
|
810
|
+
* - `fetch.patch.deferred(...)`
|
|
811
|
+
* - `fetch.post.deferred(...)`
|
|
812
|
+
* - `fetch.put.deferred(...)`
|
|
813
|
+
*
|
|
814
|
+
* @template T The type of the value that the `fetch` resolves to.
|
|
815
|
+
* @template TReturn Return value type.
|
|
816
|
+
*
|
|
817
|
+
* If `T` is not specified defaults to the following based on the value of `options.as`:
|
|
818
|
+
* - FetchAs.arrayBuffer: `ArrayBuffer`
|
|
819
|
+
* - FetchAs.blob: `Blob`
|
|
820
|
+
* - FetchAs.bytes: `Uint8Array<ArrayBuffer>`
|
|
821
|
+
* - FetchAs.formData: `FormData`
|
|
822
|
+
* - FetchAs.json: `unknown`
|
|
823
|
+
* - FetchAs.text: `string`
|
|
824
|
+
* - FetchAs.response: `Response`
|
|
825
|
+
*
|
|
826
|
+
* @param url
|
|
827
|
+
* @param options (optional) Standard `fetch` options extended with {@link FetchCustomOptions}
|
|
828
|
+
* @param options.abortCtrl (optional) if not provided `AbortController` will be instantiated when `timeout` used.
|
|
829
|
+
*
|
|
830
|
+
* Default: `new AbortController()`
|
|
831
|
+
* @param options.as (optional) (optional) specify how to parse the result.
|
|
832
|
+
* For raw `Response` use {@link FetchAs.response}
|
|
833
|
+
*
|
|
834
|
+
* Default: {@link FetchAs.json}
|
|
835
|
+
* @param options.headers (optional) request headers
|
|
836
|
+
*
|
|
837
|
+
* Default: `{ 'content-type': 'application/json' }`
|
|
838
|
+
* @param options.interceptors (optional) request interceptor/transformer callbacks.
|
|
839
|
+
* See {@link FetchInterceptors} for details.
|
|
840
|
+
* @param options.method (optional) fetch method.
|
|
841
|
+
*
|
|
842
|
+
* Default: `'get'`
|
|
843
|
+
* @param options.timeout (optional) duration in milliseconds to abort the request.
|
|
844
|
+
* This duration includes the execution of all interceptors/transformers.
|
|
845
|
+
*
|
|
846
|
+
* Default: `30_000`
|
|
847
|
+
*
|
|
848
|
+
*
|
|
849
|
+
*
|
|
850
|
+
* ---
|
|
851
|
+
*
|
|
852
|
+
* @example
|
|
853
|
+
* #### Drop-in replacement for built-in fetch
|
|
854
|
+
*
|
|
855
|
+
* ```javascript
|
|
856
|
+
* import fetch from '@superutils/fetch'
|
|
857
|
+
*
|
|
858
|
+
* fetch('https://dummyjson.com/products/1')
|
|
859
|
+
* .then(response => response.json())
|
|
860
|
+
* .then(console.log, console.error)
|
|
861
|
+
* ```
|
|
862
|
+
*
|
|
863
|
+
* @example
|
|
864
|
+
* #### Method specific function with JSON parsing by default
|
|
865
|
+
* ```javascript
|
|
866
|
+
* import fetch from '@superutils/fetch'
|
|
867
|
+
*
|
|
868
|
+
* // no need for `response.json()` or `result.data.data` drilling
|
|
869
|
+
* fetch.get('https://dummyjson.com/products/1')
|
|
870
|
+
* .then(product => console.log(product))
|
|
871
|
+
* fetch.get('https://dummyjson.com/products/1')
|
|
872
|
+
* .then(product => console.log(product))
|
|
873
|
+
*
|
|
874
|
+
*
|
|
875
|
+
* fetch.post('https://dummyjson.com/products/add', { title: 'Product title' })
|
|
876
|
+
* .then(product => console.log(product))
|
|
877
|
+
* ```
|
|
878
|
+
*
|
|
879
|
+
*
|
|
880
|
+
* @example
|
|
881
|
+
* #### Set default options.
|
|
882
|
+
*
|
|
883
|
+
* Options' default values (excluding `as` and `method`) can be configured to be EFFECTIVE GLOBALLY.
|
|
884
|
+
*
|
|
885
|
+
* ```typescript
|
|
886
|
+
* import fetch from '@superutils/fetch'
|
|
887
|
+
*
|
|
888
|
+
* const { defaults, errorMsgs, interceptors } = fetch
|
|
889
|
+
*
|
|
890
|
+
* // set default request timeout duration in milliseconds
|
|
891
|
+
* defaults.timeout = 40_000
|
|
892
|
+
*
|
|
893
|
+
* // default headers
|
|
894
|
+
* defaults.headers = { 'content-type': 'text/plain' }
|
|
895
|
+
*
|
|
896
|
+
* // override error messages
|
|
897
|
+
* errorMsgs.invalidUrl = 'URL is not valid'
|
|
898
|
+
* errorMsgs.timedout = 'Request took longer than expected'
|
|
899
|
+
*
|
|
900
|
+
* // add an interceptor to log all request failures.
|
|
901
|
+
* const fetchLogger = (fetchErr, url, options) => console.log('Fetch error log', fetchErr)
|
|
902
|
+
* interceptors.error.push(fetchLogger)
|
|
903
|
+
*
|
|
904
|
+
* // add an interceptor to conditionally include header before making requests
|
|
905
|
+
* interceptors.request.push((url, options) => {
|
|
906
|
+
* // ignore login requests
|
|
907
|
+
* if (`${url}`.includes('/login')) return
|
|
908
|
+
*
|
|
909
|
+
* options.headers.set('x-auth-token', 'my-auth-token')
|
|
910
|
+
* })
|
|
911
|
+
* ```
|
|
912
|
+
*/
|
|
913
|
+
declare const fetch: typeof fetch$1 & typeof methods;
|
|
914
|
+
|
|
915
|
+
export { type ClientData, ContentType, type ExcludeOptions, type ExcludePostOptions, type ExtractAs, type ExtractFetchAs, type FetchArgs, type FetchArgsInterceptor, FetchAs, type FetchCustomOptions, type FetchDeferredArgs, type FetchErrMsgs, FetchError, type FetchFunc, type FetchInterceptorError, type FetchInterceptorRequest, type FetchInterceptorResponse, type FetchInterceptorResult, type FetchInterceptors, type FetchInterceptorsMerged, type FetchOptions, type FetchOptionsDefault, type FetchOptionsInterceptor, type FetchResult, type FetchRetryOptions, type GetFetchResult, type IPromise_Fetch, type Interceptor, type PostArgs, type PostBody, type PostDeferredCbArgs, type PostOptions, createClient, createPostClient, fetch as default, executeInterceptors, fetch, mergeOptions };
|