sqmicro-commons
Version:
Commons for SQ analytics microservices.
51 lines (44 loc) • 1.35 kB
JavaScript
const wait = require('util').promisify(setTimeout);
const { Retrier } = require('../');
const LATENCY = 800; // ms
[{
fails: 3,
tries: 4
}, {
fails: 3,
tries: 3,
expectError: true
}, {
fails: 3,
tries: 4,
delay: 200 // while latency is 800
}].reduce(test, Promise.resolve());
function test(p, c) {
const name = `${c.fails} failures, ${c.tries} tries with ${c.delay || 5000}ms delay`;
const retrier = new Retrier(c.delay, c.tries);
const action = getAction(c.fails);
return p.then(
() => {
console.log(`START: ${name}`);
return retrier.retry(action).then(
() => console.log(`No error in ${name} ${c.expectError ? 'while it was EXPECTED!' : '.'}`),
e => console.log(`Got ${c.expectError ? 'expected' : 'UNEXPECTED'} error in ${name}: ${e}`)
).then(
() => console.log( `STOP ${name}\n\n`)
);
}
);
}
function getAction(nFailures) {
let ntries = 0;
return async function action() {
await wait(LATENCY);
ntries++;
if (ntries > nFailures) return 'yay!';
throw Error(`Try #${ntries} fails for some reason`);
};
}
process.on('unhandledRejection', (reason) => {
reason.stack;
console.error(`\nGot unhandled rejection: ${reason}`);
});