Detalhes do pacote

lb-fetch

fabrykowski139MIT1.0.2

Load balanced fetch

fetch, request, requests, http

readme (leia-me)

lb-fetch

NPM Version

A load balanced fetch.

Installation

npm i lb-fetch

Usage

import lbFetch from 'lb-fetch';

const response = await lbFetch(
  [
    "https://server1.example.com/api/endpoint",
    new URL("https://server2.example.com/api/endpoint")
  ],
  {
    method: 'POST',
    body: new URLSearchParams({
      foo: 'bar',
      baz: '42'
    })
  }
);

API

lbFetch(input, init?, options?)

Tries to fetch one of the inputs in some order until successful.

Returns a Promise of a Response.

input

Type: (string | URL)[] or generic InputType[]

The URLs to try. The input may also be an array of anything else, then options.balancer must be defined.

init

Type: RequestInit | undefined

Default: undefined

Same as fetch options.

options.fetch

Type: typeof fetch

Default: the global fetch method

Any method that conforms to the Fetch API.

options.balancer

Type: Balancer<InputType = string | URL>

type Balancer<InputType = string | URL> = (
  inputs: InputType[],
  init: RequestInit | undefined
) => Promise<(string | URL)[]> | (string | URL)[];

Default: randomBalancer

This method decides the order in which the entries of input are tried.

Note: the default value only works for inputs consisting of strings and URLs.

options.success

Type: SuccessPredicate

type SuccessPredicate = (response: Response) => boolean;

Default: reject500s

This method decides whether an attempt was successful.

If a request to an input throws an exception, it is also considered unsuccessful.

randomBalancer(input)

The default balancer returns a shuffled shallow copy of its input.

input

Type: (string | URL)[]

reject500s(response)

The default SuccessPredicate accepts a response, if its status is less than 500 – i.e. if the response was not a server error.