API

A package for managing API from any origin.
Installation
npm install @janiscommerce/api
APIDispatcher
Usage
How to dispatch an API? (from a server)
const { APIDispatcher } = require('@janiscommerce/api');
const dispatcher = new APIDispatcher({
endpoint: 'api/pets',
method: 'get',
data: { status: 'active' },
headers: { 'Content-Type': 'application/json' },
cookies: { 'my-cookie': 123 }
});
const response = await dispatcher.dispatch();
console.log(response);
API
You should extend your apis from this module.
-
pathParameters (getter). Returns the path parameters of the request.
-
headers (getter). Returns the the headers of the request.
-
cookies (getter). Returns the the cookies of the request.
-
setCode(code). Set a response httpCode. code
must be a integer.
-
setHeader(headerName, headerValue). Set an individual response header. headerName
must be a string.
-
setHeaders(headers). Set response headers. headers
must be an object with "key-value" headers.
-
setCookie(cookieName, cookieValue). Set an individual response cookie. cookieName
must be a string.
-
setCookies(cookies). Set response cookies. cookies
must be an object with "key-value" cookies.
-
setBody(body). Set the response body.
How to use the API?
const { API } = require('@janiscommerce/api');
class MyApi extends API {
get struct() {
return {
id: 'number',
name: 'string'
};
}
async validate() {
if(this.data.id > 10)
throw new Error('Weird validation fail');
if(!existsInMyDB(this.data.id)) {
this.setCode(404);
throw new Error('resource not found');
}
}
async process() {
if(!saveInMyDB(this.data))
throw new Error('internal save error');
if(!saveOtherThingInMyDB(this.data)) {
this.setCode(504);
throw new Error('internal save error');
}
this
.setHeader('my-header-1', 'foo')
.setHeaders({ 'my-header-2': 'foo', 'my-header-3': 'foo' })
.setCookie('my-cookie-1', 'bar')
.setCookies({ 'my-cookie-2': 'bar', 'my-cookie-3': 'bar' })
.setBody({
'response-body': 123
});
}
}
module.exports = MyApi;