项目作者: MatthewZito

项目描述 :
A declarative way to instantiate http clients and make serial http requests
高级语言: JavaScript
项目地址: git://github.com/MatthewZito/http-factory.git
创建时间: 2021-03-01T00:16:19Z
项目社区:https://github.com/MatthewZito/http-factory

开源协议:MIT License

下载


http-factory

Coverage Status
Continuous Deployment
Continuous Integration
npm version
License: MIT

http-factory lets you build declarative, strongly-typed http interfaces

  1. const client = new HttpClient({ ...options })
  2. // transform the outbound request / inbound response
  3. .transforms({ request: fn, response: fn })
  4. // intercept the outbound request / inbound response or error
  5. .intercepts({ request: fn, response: fn, error: fn })
  6. // log the outbound request / inbound response
  7. .logs({ request: isDev, response: isDev })
  8. // set the base url for the client instance
  9. .setBaseUrl('...');
  10. // make a serial request
  11. const data = [];
  12. for await (const rs of client.serialGet(urls)) {
  13. if (rs.status === 200) data.push({ data: rs.data });
  14. ...

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:

  1. ...
  2. client.intercepts({
  3. request: ({ data }) => ({ ok: true, data }),
  4. error: (err) => ({ ok: false, data: null, message: err.response.data.msg || 'something went wrong' }),
  5. });
  6. async function getData () {
  7. await client.getTheData({ url }, ({ ok, data }) => {
  8. if (ok) {
  9. // didn't have to do a bunch of response normalization in my component, yay
  10. } else {
  11. // handle
  12. }
  13. });
  14. }

Continuations can likewise be passed to serial requests:

  1. ...
  2. const callback = ({ data }) => results.push(data);
  3. async function fetchAll () {
  4. try {
  5. for await (const _ of client.serialGet(urls, callback));
  6. } catch(ex) { ... }
  7. }
  8. ...

See the API docs below for instantiating clients, dev logging, and making iterable requests.

For client options see Axios docs.

Installation" class="reference-link"> Installation

  1. npm install http-factory

OR

  1. yarn add http-factory

Supported Environments" class="reference-link"> Supported Environments

http-factory currently supports UMD, CommonJS (node versions >= 10), and ESM build-targets

Commonjs:

  1. const { HttpClient } = require('http-factory');

ESM:

  1. import { HttpClient } from 'http-factory';

Documentation" class="reference-link"> Documentation

Full documentation can be found here