Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

http-factory

Package Overview
Dependencies
Maintainers
1
Versions
8
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

http-factory

A declarative way to instantiate http interfaces and make iterable requests

  • 1.1.0
  • Source
  • npm
  • Socket score

Version published
Maintainers
1
Created
Source

http-factory

A Declarative Http Interface Factory

Build Status npm version License: MIT

http-factory is an NPM library and Axios-wrapper that offers a declarative way to instantiate http interfaces and make iterable (serial async) requests.

var data = [];

for await (var rs of client.serialGet(urls)) {
  if (rs.status === 200) data.push({ data: response.data });
...

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

For client options see Axios docs.

Table of Contents

Supported Environments

http-factory currently supports UMD, CommonJS (node versions >= 10), and ESM build-targets. Is your preferred build not supported? Open an issue!

Installation + Usage

npm install http-factory
# OR
yarn add http-factory

Commonjs:

const httpClient = require('http-factory');

ESM:

import httpClient from 'http-factory';

Documentation

By default, the withCredentials property is set to false. Similarly, requests are - by default - 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:


const client = new HttpClient({ baseURL: 'https://some-domain.com/api/' });

You can chain interceptors, transformers, and dev loggers onto the constructor invocation:

const client = new HttpClient({ ...options })
  .transforms({ request: fn, response: fn })
  .intercepts({ request: fn, response: fn, error: fn })
  .logs({ request: true, response: true })
  .setBaseUrl('...');

Note Interceptors expect response and error handlers to be passed together.

Core API

setBaseUrl(url: string)

set a base URL for the given client instance

Example

const client = new HttpClient({ ...options })
  .setBaseUrl('https://website.com/api');
intercepts({ request: Function, response: Function, error: Function })

register handlers for intercepting request / response

Expects named arguments to which request, response, and error interceptors will be passed.

Note Response and error each require the other. This will be fixed in v1.0.3

Example

import { request, response, error } from './interceptors';

const client = new HttpClient({ ...options })
  .intercepts({ request, response, error });
transforms({ request: (Function|Function[]), response: (Function|Function[]) })

register request / response transformers

Executes handlers on inbound / outbound request objects; fires before interceptors. Accepts Function or array thereof.

Transformers are invoked before interceptors and automatically deserialize responses, where applicable.

Example

import { request, response } from './transformers';

const client = new HttpClient({ ...options })
  .transforms({ request, response });
logs({ request: boolean, response: boolean })

toggle request/response logging

Specify whether you want to log the request and / or response headers and data.

Example

const isDevEnv = process.env.NODE_ENV === 'development';

const client = new HttpClient({ ...options })
  .logs({ request: isDevEnv, response: isDevEnv }); // logs request / response to console in dev env

Iterable Requests

serialGet(config: object[], cb: Function)

execute an iterable request, awaiting each result in sequence

Pass an array of objects (each a GET config) and iterate over the results as they resolve.

Example

const client = new HttpClient({ ...options });


var results = [];
var urls : [{ url: '/users/1' }, { url: '/users/2' }, {  url: '/users/3' }];

async function fetchAll () {
  for await (var response of client.serialGet(urls)) {
    if (response.status === 200) results.push({ data: response.data.id });
    // [ { data: 1 } ]
    // [ { data: 1 }, { data: 2 } ]
    // [ { data: 1 }, { data: 2 }, { data: 3 } ]
    ...
  }
}

Continuations / Callbacks

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:

Example


async function getData () {
  await client.getTheData({ url }, ({ ok, data }) => {
    if (ok) this.data = data;
    else ...
  });
}

FAQs

Package last updated on 23 Mar 2021

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc