gofor

Each Gofor instance exposes a fetch method: a lean fetch decorator that deep reverse merges default options.
Options you pass through in for each request will take precedence, but will supplemented with the defaults.
Install
npm i gofor
Using the constructor
const Gofor = require('gofor');
const myGofor = new Gofor({headers: {'X-Custom-Header': 'Custom-Value'}});
myGofor.fetch('/page')
.then(...)
.catch(...);
"out of the box" usability with instances
const {gofor} = require('gofor');
gofor('/page').then(...);
gofor.config({headers: {'X-Custom-Header': 'Custom-Value'}});
gofor('/page').then(...);
Configuring an instance
const {gofor} = require('gofor');
const defaultHeaders = new Headers();
defaultHeaders.append('X-Requested-With', 'XMLHttpRequest');
defaultHeaders.append('Content-Type', 'application/json; charset=utf-8');
defaultHeaders.append('Accept', 'application/json');
gofor.config({
credentials: 'same-origin',
headers: defaultHeaders
});
gofor('https://www.website.com').then(...);
gofor('/page', {
headers: {
'X-Custom-Header': 'Custom-Value'
}
}).then(...);
Default header keys will be run over if matched by passed in header keys. Other keys will be merged. This is made by design.
Example
gofor.config({
credentials: 'same-origin',
headers: new Headers({
'Content-Type': 'application/json; charset=utf-8',
'X-Custom-Header': 'Custom-Value'
})
});
gofor('/page', {
headers: new Headers({
'Content-Type': 'text/plain',
})
});
Final headers will be:
'Content-Type': 'text/plain',
'X-Custom-Header': 'Custom-Value'
Each gofor getter creates a new instance
const gofor1 = require('gofor').gofor;
const gofor2 = require('gofor').gofor;
gofor1 === gofor2
Delayed configuration
The function will be called once on first use, and its result will be memoised. useful for cases where you need to pull information from the document and don't want to create a race condition.
const {gofor} = require('gofor');
gofor.config(() => ({
credentials: 'same-origin',
headers: {
'X-Requested-With': 'XMLHttpRequest',
'Content-Type': 'application/json; charset=utf-8',
'Accept': 'application/json',
'X-Custom-Secret': document.getElementById('secret').value,
},
}));
Node Runtime
Gofor brings a pre baked node compatible flavour using node-fetch.
const {gofor} = require('gofor/node');
Bundled version
Environments which exclude node_modules from the transpiling pipeline should include the "browser" entry instead of "main". This exposes a bundled ES5 commonjs module.
Also available for explicit import:
const {gofor} = require('gofor/dist');