fail4ward-retry v0.2.3
fail4ward-retry
NPM package to implement Retry Pattern in your nodejs applications. Created from this Cookiecutter Template.
Features
- Uses the builder pattern, implementation is similar to
resilience4j
. - Uses the ardydedase/fail4ward docker image to run a service to test with.
- Uses testcontainers-node to test against a running docker service.
- Supports
UntilLimit
strategy. Based on the Medium article SRE: Resiliency: Retries in Action — Availability in Exchange for Latency
Specs
Tested on:
- npm 6.13.4
- node v10.19.0
Installation
npm install --save fail4ward-retry
Usage
Import what we need.
import { RetryConfigBuilder, RetryConfig, Retry, UntilLimit } from 'fail4ward-retry';
Set the configuration using the RetryConfigBuilder()
.
const maxAttempts = 5;
const waitDuration = 1000;
const retryConfig: RetryConfig = new RetryConfigBuilder()
.withMaxAttempts(maxAttempts)
.withWaitDuration(waitDuration)
.withStrategy(UntilLimit)
.build();
Builder properties we are setting
withMaxAttempts()
number of attempts to retry.withWaitDuration()
backoff time in milliseconds.withStrategy()
retry strategy to use. This package currently supportsUntilLimit
.
Decorate the function that calls your service using the retryConfig instantiated with Retry.decoratePromise()
.
const retry = Retry.With(retryConfig);
const fn = retry.decoratePromise(failingFn);
Below is an example of the failingFn
calls an API. Similar functions can be found in the /example and /__tests__ folders.
async function failingFn() {
const url = 'http://localhost:8000/error';
try {
const res = await fetch(url);
const {status} = res;
if (status === 500) {
throw new Error('server error');
}
return res;
} catch(e) {
throw new Error(e);
}
}
Call the function that fetches the response from your API and retrieve the response.
try {
const res = await fn();
const retryResponse = await res.json();
console.log('retryResponse: ', retryResponse);
} catch(e) {
console.log(e);
}
Run the example
Checkout the repo
git clone git@github.com:ardydedase/fail4ward-retry.git
Change directory to the
example
foldercd example/
Install dependencies
npm install
Run a test service
docker run --name fail-svc -p 8000:8000 -it ardydedase/fail4ward:latest
Run the example file
npm run dev
Development
- Checkout the repo
git clone git@github.com:ardydedase/fail4ward-retry.git
Install dependencies
npm install
Run build. This will generate the compiled code with type definitions in the
dist
folder.npm run build
Formatting and linting.
npm run lint npm run format
Run tests
npm test