0.12.1 • Published 30 days ago

@sampullman/fetch-api v0.12.1

Weekly downloads
-
License
MIT
Repository
github
Last release
30 days ago

Instructions

Install

npm i -D @sampullman/fetch-api
yarn add @sampullman/fetch-api
pnpm i -D @sampullman/fetch-api

Configuration

FetchApi global configuration is passed to the constructor.

FetchApi({
  // API base URL prepended to requests
  baseUrl: '',

  // Default request timeout
  timeout: 10000,

   // Passed to JSON.stringify and used as fetch `body`.
   // Sets headers: { Accept: 'application/json', 'Content-Type': 'application/json' }
  data: null,

  // Request URL parameters, e.g. `{ 'a': 1 }`. Passed to `new URLSearchParams(params)`
  // Entries with undefined values are filtered out
  params: RequestParams,

  // Convenience for Basic Auth.
  // Sets headers['Authorization'] = `Basic ${btoa(`${auth.username}:${auth.password}`)}`
  auth: { username: 'test', password: 'password' }

  // Request interceptors
  requestInterceptors: [],

  // Response interceptors
  responseInterceptors: [],
});

Usage

Here is an example of basic usage that includes a response interceptor for handling 403 response codes and converting the body to json.

const api = new FetchApi({
  baseUrl: 'https://cool.api/',
  responseInterceptors: [
    async (res) => {
      const { status } = res;

      if (status === 403) {
        throw new Error('FORBIDDEN');
      }
      res.data = await res.json();
      return res;
    },
  ],
});

// Make a get request to 'https://cool.api/status/'
const status = api.request({ url: 'status/' });

Environment

fetch must be available. If you need to support older browsers or Node, use a polyfill such as whatwg-fetch

Example

See the example directory.

License

MIT License © 2021 Samuel Pullman

0.12.0

30 days ago

0.12.1

30 days ago

0.11.4

5 months ago

0.11.5

5 months ago

0.11.0

1 year ago

0.10.1

1 year ago

0.11.1

1 year ago

0.11.2

1 year ago

0.11.3

1 year ago

0.10.0

1 year ago

0.9.2

1 year ago

0.9.0

1 year ago

0.9.1

1 year ago

0.8.1

2 years ago

0.7.0

2 years ago

0.6.0

2 years ago

0.5.0

3 years ago

0.4.0

3 years ago

0.3.2

3 years ago

0.3.1

3 years ago

0.3.0

3 years ago

0.2.1

3 years ago

0.2.2

3 years ago

0.1.7

3 years ago

0.1.6

3 years ago

0.1.3

3 years ago

0.1.0

3 years ago