UNPKG

readiness-manager

Version:

👨‍💼 Define when your app is ready

71 lines (50 loc) 2.17 kB
## Motivation In many cases node application depends on external resources that should be available before truly starting up. This manager gives you the ability to orchestrate several actions independently. It is waiting for their completion to defines your app readiness state. This comes truly handy when your application runs inside Kubernetes which can check its readiness state. ## Getting started Register at any point an async action with a declarative alias and run them once your app starts. ```js // app.index.js const axios = require('axios'); const ReadinessManager = require('readiness-manager'); ReadinessManager.register('vendors', () => axios.get('https://www.cdn.vendors.com')); ReadinessManager.register('translations', () => axios.get('https://www.translations.com')); // Starts all registered actions ReadinessManager.run(); // Will be triggered once all registered actions are successfully resolved. ReadinessManager.onReady(() => console.log('App is ready! o/')); ``` This will allow you to set up an health check route, checking if you app readiness state as following: ```js // routes.health.js if (ReadinessManager.ready) { res.status(200).end(`App is ready and running well`); return; } else { res.status(503).end('App is not ready'); } ``` ## Errors handling You can register an error handler over the manager, which will be triggered from any thrown error from it's registered actions. Once an error rises, the manager will trigger the error handler with both occurred error and a `retry` method used to re-execute the failing action if desired. > The default error handle will just log errors to console and thus strongly recommended to register your own handler. ```js // app.index.js const ReadinessManager = require('readiness-manager'); let count = 0; const unstableAction = () => new Promise((resolve, reject) => { count++; if (counter <= 1) { return reject(new Error('Not yet')); } resolve('Ok'); }); ReadinessManager.register('action', unstableAction); ReadinessManager.onError((error, retry) => { console.log(error); if (error.attempt <= 1) retry(); }); ReadinessManager.run(); ```