REST-API helper, wrapped around
fetch
.
npm i --save unity-api
Returns: {Object}
Use module's default export
to create an API object.
An API would be redundant without any of resources defined.
Each resource represents an entity in your REST-API as an object
with the following properties:
Namespace of an entity. e.g.: example.com/api/user/get
Dictionary of facade-methods that transform your api calls params to fetch
calls params.
Each method should return a plain object
with the following properties:
Default: ''
If path is an array
, items will be joined and normalized.
Default: {}
Query-like object.
Default: {}
fetch
options.
Default: 'json'
Method to be called on fetch
's response.
Alternatively you can use provided shortcuts for every HTTP method
Example:
import { GET, HEAD, POST, PUT, DELETE, CONNECT, OPTIONS, TRACE, PATCH } from '../src/shortcuts';
const userResource = {
namespace: 'user',
methods: {
// id = 1, extanted = true
// GET: /api/user/1?extended=true
get: ({ id, extended }) => ({ path: [id], query: { extended: !!extended } }),
// POST: /api/user/1/edit
save: ({ id, firstname, lastname }) => {
const formData = new FormData();
formData.append('firstname', firstname);
formData.append('lastname', lastname);
return {
path: [id, 'edit'],
options: {
method: 'POST',
body: formData
}
};
},
// DELETE: /api/user/1
delete: ({ id }) => DELETE({ path: [id] })
}
}
An array of middleware functions, that can manipulate an api call, its params and its result, along with options for the remaning middleware in chain.
const myMiddleware = next => async (options, params, resource, method) => { return await next() }
An async
function, that calls next middleware in chain, or, in case of last middleware, the api method itself.
Middleware parameters, that an api call was made with.
Parameters, that an api call was made with.
Name of the resource, whose method was called.
Name of the method called
Example logger middleware:
export default next => async (middlewareOptions, apiCallParams, resource, method) => {
console.log('args', { middlewareOptions, apiCallParams, resource, method }); // eslint-disable-line no-console
const result = await next();
console.log('result', result); // eslint-disable-line no-console
return result;
};
Default: 'api'
Usually you would want to proxy api calls from the SPA to the backend using some common namespace. e.g. example.com/api/user/get
Default:
{
method: 'GET',
mode: 'cors',
cache: 'default',
credentials: 'include'
}
API-wide default fetch
options.
You can call your API methods like so:
API[resource][method](methodParams, middlewareOptions)
Create API module:
// api.js
import createAPI from 'unity-api';
const resources = {
user: {
namespace: 'user',
methods: {
get: ({ id }) => ({ path: id }),
delete: ({ id }) => ({ path: id, options: { method: 'DELETE' } }),
}
}
}
const logger = next => async (middlewareOptions, apiCallParams, resource, method) => {
const { log } = middlewareOptions;
if (log) {
console.log('args', { middlewareOptions, apiCallParams, resource, method }); // eslint-disable-line no-console
}
const result = await next();
if (log) {
console.log('result', result); // eslint-disable-line no-console
}
return result;
};
const middleware = [
logger
]
fetchOptions = {
method: 'GET',
mode: 'cors',
cache: 'default',
credentials: 'include'
}
const API = createAPI(resources, middleware, 'api', fetchOptions);
export default API;
Use it in your application:
// index.js
import API from './api';
const user = await API.user.get({ id: 1 }, { log: true });
- Provide conventional commit messages by using
npm run commit
instead ofgit commit
. - Core contributors: use GitHub's Rebase and merge as a default way of merging PRs.
MIT © AuRu