All files / src/hof resilient.js

8.33% Statements 1/12
0% Branches 0/4
0% Functions 0/2
8.33% Lines 1/12
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38    1x                                                                      
import { VError, MultiError } from 'verror';
 
const DEFAULT_CONFIG = {
	task: 'promise resolution',
	attempts: 3,
	context: null
};
 
export default function resilient(asyncFn, config) {
	config = {
		...DEFAULT_CONFIG,
		...(config || {})
	};
 
	const errors = [];
	const maxAttempts = config.attempts;
 
	async function resilientFn(...args) {
		try {
			return await asyncFn.apply(config.context, args);
		} catch (err) {
			if (config.attempts <= 0) {
				// give up
				throw new VError({
					name: 'ResilientPromiseFailed',//
					cause: new MultiError(errors),
					info: { task: config.task, maxAttempts }
				}, `Resilient ${config.task} failed after ${maxAttempts}`);
			} else {
				config.attempts -= 1;
				errors.push(err);
				return resilientFn(...args);
			}
		}
	}
 
	return resilientFn;
}