Load balanced fetch
npm install lb-fetch
A load balanced fetch.
``bash`
npm i lb-fetch
`javascript
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'
})
}
);
`
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, thenoptions.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
`typescript`
type Balancer
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 andURLs.
#### options.success
Type: SuccessPredicate
`typescript`
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.
The default balancer returns a shuffled shallow copy of its input.
#### input
Type: (string | URL)[]
The default SuccessPredicate accepts a response, if its status is less than500` – i.e. if the response was not a server error.