http-factory
http-factory
lets you build declarative, strongly-typed http interfaces
const client = new HttpClient({ ...options })
.transforms({ request: fn, response: fn })
.intercepts({ request: fn, response: fn, error: fn })
.logs({ request: isDev, response: isDev })
.setBaseUrl('...');
const data = [];
for await (const rs of client.serialGet(urls)) {
if (rs.status === 200) data.push({ data: rs.data });
...
By default, requests are sent with a Content-Type header of application/json. UTF-8 encoding is set by default, and all request bodies will be serialized.
To change this behavior, you can provide your own Axios options to the constructor.
Each request method accepts an optional callback to which the response or error will be piped. This affords the use of continuation-passing using callbacks:
...
client.intercepts({
request: ({ data }) => ({ ok: true, data }),
error: (err) => ({ ok: false, data: null, message: err.response.data.msg || 'something went wrong' }),
});
async function getData () {
await client.getTheData({ url }, ({ ok, data }) => {
if (ok) {
} else {
}
});
}
Continuations can likewise be passed to serial requests:
...
const callback = ({ data }) => results.push(data);
async function fetchAll () {
try {
for await (const _ of client.serialGet(urls, callback));
} catch(ex) { ... }
}
...
See the API docs below for instantiating clients, dev logging, and making iterable requests.
For client options see Axios docs.
Installation
npm install http-factory
OR
yarn add http-factory
Supported Environments
http-factory
currently supports UMD, CommonJS (node versions >= 10), and ESM build-targets
Commonjs:
const { HttpClient } = require('http-factory');
ESM:
import { HttpClient } from 'http-factory';
Documentation
Full documentation can be found here