@superutils/fetch 1.2.2 → 1.2.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -193,10 +193,11 @@ setTimeout(() => {
193
193
  3. `ResolveIgnored.NEVER`: The promise for the aborted "iphone" request is neither resolved nor rejected.
194
194
  It will remain pending indefinitely.
195
195
  - **`resolveError` (enum)**: Controls how failed requests are handled.
196
- 1. `ResolveError.NEVER`: Never resolve ignored promises. Caution: make sure this doesn't cause any memory leaks.
197
- 2. `ResolveError.WITH_LAST`: (default) resolve with active promise result, the one that caused the current promise/callback to be ignored.
198
- 3. `ResolveError.WITH_UNDEFINED`: resolve failed requests with `undefined` value
199
- 4. `ResolveError.WITH_ERROR`: The promise for the aborted "iphone" request is rejected with a `FetchError`.
196
+ 1. `ResolveError.NEVER`: The promise for a failed request will neither resolve nor reject, causing it to remain pending indefinitely.
197
+ > **Warning:** Use with caution, as this may lead to memory leaks if not handled properly.
198
+ 2. `ResolveError.WITH_ERROR`: The promise resolves with the `FetchError` object instead of being rejected.
199
+ 3. `ResolveError.WITH_UNDEFINED`: The promise resolves with an `undefined` value upon failure.
200
+ 4. `ResolveError.REJECT`: (Default) The promise is rejected with a `FetchError`, adhering to standard promise behavior.
200
201
 
201
202
  #### Using defaults to reduce redundancy
202
203
 
@@ -314,6 +315,7 @@ const requestNewToken = fetch.post.deferred(
314
315
  )
315
316
 
316
317
  // First authenticate user to get the initial refresh token and then request new referesh tokens
318
+ // First authenticate user to get the initial refresh token and then request new refresh tokens
317
319
  fetch
318
320
  .post<{ refreshToken: string }>(
319
321
  'https://dummyjson.com/auth/login',
@@ -360,74 +362,86 @@ The following interceptor callbacks allow intercepting and/or transforming at di
360
362
  - Value returned (transformed) by an interceptor will be carried over to the subsequent interceptor of the same type.
361
363
  - There are 2 category of interceptors:
362
364
  - Local: interceptors provided when making a request.
363
- - Global: intereptors 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.
364
365
 
365
- **Example: Add global request and error interceptors**
366
+ **Example: Interceptor usage**
366
367
 
367
368
  ```javascript
368
- import fetch from '@superutils/fetch'
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
+ ```
369
418
 
370
- const { interceptors } = fetch.defaults
371
- interceptors.request.push((url, options) => {
372
- // a headers to all requests make by the application
373
- options.headers.append('x-auth', 'token')
374
- })
419
+ - 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.
375
420
 
376
- interceptors.error.push((err, url, options) => {
377
- // log whenever a request fails
378
- console.log('Error interceptor', err)
379
- })
380
- ```
421
+ **Example: Add global request and error interceptors**
381
422
 
382
- ```javascript
383
- import fetch, { FetchError } from '@superutils/fetch'
384
-
385
- const interceptors = {
386
- error: [
387
- (err, url, options) => {
388
- console.log('Request failed', err, url, options)
389
- // return nothing/undefined to keep the error unchanged
390
- // or return modified/new error
391
- err.message = 'My custom error message!'
392
- // or create a new FetchError by cloning it (make sure all the required properties are set correctly)
393
- return err.clone('My custom error message!')
394
- },
395
- ],
396
- request: [
397
- (url, options) => {
398
- // add extra headers or modify request options here
399
- options.headers.append('x-custom-header', 'some value')
400
-
401
- // transform the URL by returning a modified URL
402
- return url + '?param=value'
403
- },
404
- ],
405
- response: [
406
- (response, url, options) => {
407
- if (response.ok) return
408
- console.log('request was successful', { url, options })
409
-
410
- // You can transform the response by returning different `Response` object or even make a completely new HTTP reuqest.
411
- // The subsequent response interceptors will receive the returned response
412
- return fetch('https://dummyjson.com/products/1') // promise will be resolved automatically
413
- },
414
- ],
415
- result: [
416
- (result, url, options) => {
417
- const productId = Number(
418
- new URL(url).pathname.split('/products/')[1],
419
- )
420
- if (options.method === 'get' && !Number.isNaN(productId)) {
421
- result.title ??= 'Unknown title'
422
- }
423
- return result
424
- },
425
- ],
426
- }
427
- fetch
428
- .get('https://dummyjson.com/products/1', { interceptors })
429
- .then(product => console.log({ product }))
430
- ```
423
+ ```javascript
424
+ import fetch from '@superutils/fetch'
425
+
426
+ const { interceptors } = fetch.defaults
427
+
428
+ interceptors.request.push((url, options) => {
429
+ // a headers to all requests make by the application
430
+ // add headers to all requests made by the application
431
+ options.headers.append('x-auth', 'token')
432
+ })
433
+
434
+ interceptors.error.push((err, url, options) => {
435
+ // log whenever a request fails
436
+ console.log('Error interceptor', err)
437
+ })
438
+
439
+ // Each time a requst is made using @superutils/fetch, the above interceptors will be executed when appropriate
440
+ fetch('https://dummyjson.com/products/1').then(
441
+ console.log,
442
+ console.warn,
443
+ )
444
+ ```
431
445
 
432
446
  <div id="retry"></div>
433
447
 
@@ -499,33 +513,91 @@ fetch.get('https://dummyjson.com/products/1', {
499
513
 
500
514
  <div id="reusable-clients"></div>
501
515
 
502
- ### `createClient(method, )`: Reusable Clients
516
+ ### `createClient(fixedOptions, commonOptions, commonDeferOptions)`: Reusable Clients
517
+
518
+ The `createClient` utility streamlines the creation of dedicated API clients by generating pre-configured fetch functions. These functions can be equipped with default options like headers, timeouts, or a specific HTTP method, which minimizes code repetition across your application. If a method is not specified during creation, the client will default to `GET`.
503
519
 
504
- The `createClient` utility allows you to generate pre-configured fetch functions with default options, such as headers, timeouts, or specific HTTP methods. This is ideal for creating dedicated API clients for specific services to avoid repetition.
520
+ The returned client also includes a `.deferred()` method, providing the same debounce, throttle, and sequential execution capabilities found in functions like `fetch.get.deferred()`.
505
521
 
506
522
  ```javascript
507
523
  import { createClient } from '@superutils/fetch'
508
524
 
509
- // Create a client with default headers and a 5-second timeout
510
- const apiClient = createClient(undefined, {
511
- headers: {
512
- Authorization: 'Bearer my-secret-token',
513
- 'Content-Type': 'application/json',
525
+ // Create a "GET" client with default headers and a 5-second timeout
526
+ const apiClient = createClient(
527
+ {
528
+ // fixed options cannot be overridden
529
+ method: 'get',
514
530
  },
515
- timeout: 5000,
516
- })
531
+ {
532
+ // default options can be overridden
533
+ headers: {
534
+ Authorization: 'Bearer my-secret-token',
535
+ 'Content-Type': 'application/json',
536
+ },
537
+ timeout: 5000,
538
+ },
539
+ {
540
+ // default defer options (can be overridden)
541
+ delayMs: 300,
542
+ retry: 2, // If request fails, retry up to two more times
543
+ },
544
+ )
517
545
 
518
546
  // Use it just like the standard fetch
519
- apiClient('https://dummyjson.com/products/1').then(console.log)
547
+ apiClient('https://dummyjson.com/products/1', {
548
+ // The 'method' property cannot be overridden as it is used in the fixed options when creating the client.
549
+ // In TypeScript, the compiler will not allow this property.
550
+ // In Javascript, it will simply be ignored.
551
+ // method: 'post',
552
+ timeout: 3000, // The 'timeout' property can be overridden
553
+ }).then(console.log, console.warn)
554
+
555
+ // create a deferred client using "apiClient"
556
+ const deferredClient = apiClient.deferred(
557
+ { retry: 0 }, // disable retrying by overriding the `retry` defer option
558
+ 'https://dummyjson.com/products/1',
559
+ { timeout: 3000 },
560
+ )
561
+ deferredClient({ timeout: 10000 }) // timeout is overridden by individual request
562
+ .then(console.log, console.warn)
563
+ ```
564
+
565
+ ### `createPostClient(mandatoryOptions, commonOptions, commonDeferOptions)`: Reusable Post-like Clients
566
+
567
+ While `createClient()` is versatile enough for any HTTP method, `createPostClient()` is specifically designed for methods that require a request body, such as `DELETE`, `PATCH`, `POST`, and `PUT`. If a method is not provided, it defaults to `POST`. The generated client accepts an additional second parameter (`data`) for the request payload.
568
+
569
+ Similar to `createClient`, the returned function comes equipped with a `.deferred()` method, enabling debounced, throttled, or sequential execution.
520
570
 
521
- // Create a specialized POST client
522
- const createProduct = createClient(
523
- 'get', // if provided will force all requests to be of this
571
+ ```javascript
572
+ import { createPostClient, FetchAs } from '@superutils/fetch'
573
+
574
+ // Create a POST client with 10-second as the default timeout
575
+ const postClient = createPostClient(
576
+ {
577
+ method: 'post',
578
+ headers: { 'content-type': 'application/json' },
579
+ },
524
580
  { timeout: 10000 },
525
581
  )
526
582
 
527
- // No need to specify method: 'post'
528
- createProduct('https://dummyjson.com/products/add', {
529
- body: JSON.stringify({ title: 'New Product' }),
530
- }).then(console.log)
583
+ // Invoking `postClient()` automatically applies the pre-configured options
584
+ postClient(
585
+ 'https://dummyjson.com/products/add',
586
+ { title: 'New Product' }, // data/body
587
+ {}, // other options
588
+ ).then(console.log)
589
+
590
+ // create a deferred client using "postClient"
591
+ const updateProduct = postClient.deferred(
592
+ {
593
+ delayMs: 300, // debounce duration
594
+ },
595
+ 'https://dummyjson.com/products/1',
596
+ {
597
+ method: 'patch',
598
+ timeout: 3000,
599
+ },
600
+ )
601
+ updateProduct({ title: 'New title 1' }) // ignored by debounce
602
+ updateProduct({ title: 'New title 2' }) // executed
531
603
  ```