Interfacer.js
Interfacer.js is a convenient module for work with RESTful API from Client.
Key Features:
- Unopinionated about frameworks you use
- Highly customizable
- Memoization
- Simple IO error handling, that fits your system
- Customizable query construction
How to install
yarn add interfacer
or
npm install interfacer --save
Configuration & Interface Creation
The most advanced feature Interfacer.js provides is 3 level of configuration (Application, Interface, Call). In configuration you can define things like defaultError
, domain
, protocol
, and custom queryparser
. Each level of configuration overrides previous (more global ones), so you can change everything, mid-action, on the fly if you need to.
Don't panic when you see all them references to Redux like dispatch
. Their's purpose is purely illustrative. you can provide any kind of function, that handles your data.
Application Level
import interfacer from 'interfacer';
const globalConfig = {
protocol: 'https',
domain: 'localhost',
port: 8000,
defaultError: new Error('Something broke'),
errorHandler: ({error, message}) => dispatch({ type: 'API_ERROR', payload: message })
}
const createInterface = interfacer(globalConfig);
All of above settings will apply to every interface you create by this createInterface
function, unless overwritten by later configurations in more "local" level.
Interface level
Also can be perceived as "collection level". In for example Redux I'd recommend to have one interface for each collection reducer.
const localConfig = {
defaultError: new Error('Articles API error'),
constructFields: FieldsConstructor,
headers: { 'Content-Type': 'text/html' }
request: { mode: 'cors' },
errorHandler: err => dispatch({ type: 'API_ERROR', payload: err })
}
const articleInterface = createInterface('/articles', localConfig);
On Interface level you always specify subdomain
. That is route that will be appended to domain
in all requests you do, with this interface.
Obviously you can (and will) have many different Interfaces.
Call level
This final and most local level references to a certain calls you make with your interface. .send()
triggers the fetch and returns a promise.
const reqOptions = {
query: { fields: ['title', 'author']},
defaultError: new Error('Articles Collection failed to fetch')
};
articleInterface
.getCollection(reqOptions)
.then(data =>
dispatch({ type: 'RECIEVE_ARTICLES', payload: data.payload })
);
Overview
Once you've created your interface network and configured it, it's time for you to do some fetching. Every interface has following methods get
, getCollection
, update
, create
and remove
. Once called, each function returns a Promise, that contains response of the fetch
as a frist parameter. Here is their API annotation.
get
args:
id :string | number, options :Object = {}
getCollection
args:
options :Object = {}
create
args:
body :Object, options? :Object
remove
args:
id :ID, options? :Object
update
args:
id :string, body :Object, options? :Object
API Reference
Config Properties
Property | Meaning | Type | Default |
---|
error | Error that gets sent to you via throwError fn once it occures | string or object | "unhandled" |
defaultError | If no error is found, defaultError gets sent to you | string or object | "unhandled" |
errorHandler | Function that gets called if error occurs. As first argument your error will be passed | console.error | |
headers | Object containting headers your request should have | object | "Content-Type": "application/json" |
request | This object will be added to request options. It's the same as pasting an object into second argument of fetch function | {} | |
query | Object that gets passed to queryparser fn | object | null |
port | Number that gets appended to your domain | number or string or nothing | null |
domain | baseUrl that your API runs on | string | localhost |
protocol | Gets prepended to your domain | http or https | http |
queryparser | Function that transform query object into a query string | function | queryparser |
URL Queries
You can pass your own queryparser
into any config, but you can also use default one. Annotation of queryparser
looks like this
queryparser(query :Object) => string
Default queryparser
builds queries like this...
queryparser({
filters: 'over18',
fields: ['title', 'years old']
});
Thank you
Thank you for using this package. If you have any issues, questions or suggestions, create an issue please, I'll be happy to answer it.