@tailored-apps/api-connector
@tailored-apps/api-connector contains some helper-functions and is part of the api-skeleton-2.
Installation and Updating
npm install @tailored-apps/api-connector
Functions
getRequestSpec
Returns the options object used by the request function.
Endpoint specs can contain "getPath", "getQuery" and "getBody" functions - if present, these will be called (with request
params passed in) and their return value will be used for request path, query string and body respectively.
Otherwise, params will be sent in request body for requests that can have one (post, patch, put) or in the query string for
requests that cannot have a body (get & co).
function getRequestSpec (baseUrl, endpoint, params)
returns:
{ baseUrl: *, method: *, uri: string, qs: {}, json: boolean, body: undefined }
Endpoint spec properties
Property | Description |
---|
route | Endpoint uri ("/users", "/foo?bar={baz}&some={thing}") |
method | Request method |
doReplace | Attempt to replace tokens in request path (e.g. replace "{foo}" with value of params.foo in request path - will only be ignored if a getPath function has been provided) |
getPath | (optional) Function that will be called to determine request path. Called with "route" and "params" passed in, expected to return a string. |
getQuery | (optional) Function that will be used to determine query params. Called with "params" passed in, expected to return an object. |
getBody | (optional) Function that will be called to determine request body. Called with "params" passed in, expected to return an object. Will not be called for requests that cannot have a body. |
getConnector
Returns an async api connector function that can be used to access api endpoints in a simple and consistent manner.
This function expects an api baseUrl as well as a list of endpoint specs and a logger object.
Endpoint specs are objects specifying various endpoint characteristics, such as the endpoint uri and the request method.
The basic idea here is to abstract away the actual details of each endpoint and instead allow clients to simply get
data from or send data to an endpoint by calling a simple function and passing in their data as an object. Endpoint
URIs therefore need not be known to callers, and neither do they need to know about the actual API url or request methods.
returns:
{ function(*=, *=) }
Usage
An endpoint to get a particular user might be specified as follows:
{
id: 'user_details',
method: 'get',
uri: '/users/{id}'
}
To access the endpoint, clients would implement the following code:
const callApi = getConnector({ baseUrl: 'https://foo.bar/v1', endpoints: [ ... ], logger: myLoggerInstance })
const userData = await callApi('user_details', { id: 420 })
The {id} token in the endpoint uri will automatically be replaced by the value of the id property of the passed in params object.