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)
.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({
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: {
request: request => {
},
error: error => {
},
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