0.0.8 ā€¢ Published 14 days ago

@akiyamka/extended-fetch v0.0.8

Weekly downloads
-
License
ISC
Repository
-
Last release
14 days ago

extended-fetch

NPM Version NPM Type Definitions spring-easing's badge Module type: ESM Module type: CJS

Currently, there is no way to determine that the reason the request failed is due to the Timeout Error using the fetch API, but sometimes it needed, for example, for meaningful UI reaction.

The most popular workaround for this today is to set a forced limit on the client side, which will only work if it less than the existing limit outside, and it will also break functionality in situations where the limit has been raised above the standard limit

This library allows you to cath Timeout Error without enforcing a time restriction

šŸ¤ Tiny size šŸ§© Does not patching existing fetch, just exports own implementation
šŸ”€ Can be used as drop in replacement for fetch

āš ļø It's not a fetch polyfill. It uses Request and Response objects from fetch implementation

Installation

npm install @akiyamka/extended-fetch

Usage

Works just like native fetch, but with few additional features:

Catch timeout error

Fetch does not allow the user to know if his request was failed due to a 504 error.
Instead it throws common TypeError: Failed to fetch
But extended-fetch throw 'Timeout Error' error for that case

import { fetch, isTimeoutError } from 'extended-fetch';

fetch('/users', {
  method: 'POST',
  body: JSON.stringify({ foo: 'bar' }),
}).catch((error) => {
  // Allow identify timeout error
  console.assert(error.message, 'Timeout Error');
  console.assert(isTimeoutError(error), true);
});

Subscribe to xhr events:

Also you can hook XMLHttpRequest events:

import { fetch } from 'extended-fetch';

fetch(
  '/users',
  {
    method: 'POST',
    body: JSON.stringify({ foo: 'bar' }),
  },
  {
    // Extra setting
    eventListener: (event) => {
      if (event.type === 'progress') {
        console.log(`Progress changed to ${event.payload}`);
      }
    },
  }
)

Catch Abort error

The library has a typed helper for Abort error detection

import { fetch, isAbortError } from 'extended-fetch';

const abortController = new AbortController()
abortController.abort()
try {
  const reference = await fetch(srv.readyCheck(), {
    signal: abortController.signal,
  })
} catch(err) {
  if (isAbortError(e)) {
    // request was aborted
  }
}

Credits

Inspired by https://github.com/JakeChampion/fetch

0.0.8

14 days ago

0.0.7

19 days ago

0.0.6

19 days ago

0.0.5

20 days ago

0.0.4

20 days ago

0.0.3

20 days ago

0.0.2

20 days ago

0.0.1

20 days ago