@sampullman/fetch-api
TypeScript icon, indicating that this package has built-in type declarations

0.12.1 • Public • Published

@sampullman/fetch-api

Small fetch wrapper for creating quick API wrappers


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

Readme

Keywords

Package Sidebar

Install

npm i @sampullman/fetch-api

Weekly Downloads

574

Version

0.12.1

License

MIT

Unpacked Size

52.6 kB

Total Files

67

Last publish

Collaborators

  • sampullman