bivrost-fetch-adapter

3.2.2 • Public • Published

Bivrost fetch adapter

Adapter for browser's native fetch function.

yarn add bivrost-fetch-adapter

Usage

With Bivrost:

import DataSource from 'bivrost/data/source';
import bivrostApi from 'bivrost/http/api';
import fetchAdapter from 'bivrost-fetch-adapter';
 
const api = bivrostApi({
  host: 'localhost',
  adapter: fetchAdapter(),
});
 
class UsersDataSource extends DataSource {
  static api = {
    loadAll: api('GET /users'),
  };
 
  loadUsers(filters) {
    return this.invoke('loadAll', filters);
  }
}

Direct calls:

import fetchAdapter from 'bivrost-fetch-adapter';
 
const api = fetchAdapter();
 
const options = {
  method: 'GET',
  query: {
    groupId: 10,
  },
  headers: {
    'Content-Type': 'application/json',
  },
};
 
api('/users', options) // /users?groupId=10
  .then(json => {
    // ...
  })
  .catch(response => {
    // ...
  });
 
const options = {
  method: 'POST',
  body: {
    name: 'kek',
  },
  headers: {
    'Content-Type': 'application/json',
  },
};
 
api('/user/1', options)
  .then(json => {
    // ...
  })
  .catch(response => {
    // ...
  });

Configuration

import fetchAdapter from 'bivrost-fetch-adapter';
 
const api = fetchAdapter({
  // default options for each request with created adapter
  options: {
    mode: 'cors',
    redirect: 'follow',
  },
});

Available options:

  • headers - associated Headers object
  • referrer - referrer of the request
  • mode - cors, no-cors, same-origin
  • credentials - should cookies go with the request? omit, same-origin
  • redirect - follow, error, manual
  • integrity - subresource integrity value
  • cache - cache mode (default, reload, no-cache)

Interceptors

import fetchAdapter from 'bivrost-fetch-adapter';
 
const api = fetchAdapter({
  interceptors: {
    // takes Request instance as argument
    request: request => {
      // ...
    },
 
    error: error => {
      // ...
    },
 
    // takes Response instance as argument
    response: response => {
      // ...
    },
  },
});

Interceptor example:

import fetchAdapter from 'bivrost-fetch-adapter';
 
const api = fetchAdapter({
  interceptors: {
    request: request => {
      request.headers.set('Content-Type', 'application/json');
      request.headers.set('access_token', Auth.accessToken);
 
      return request;
    },
 
    error: error => Promise.reject(error);
    response: response => Promise.resolve(response)
  }
});

Fetch polyfill

Github whatwg-fetch - https://github.com/github/fetch


Bivrost allows to organize a simple interface to asyncronous APIs.

Other adapters

Package Sidebar

Install

npm i bivrost-fetch-adapter

Weekly Downloads

9

Version

3.2.2

License

ISC

Unpacked Size

9.89 kB

Total Files

6

Last publish

Collaborators

  • tuchk4