Skip to content

Instantly share code, notes, and snippets.

@formix
Last active February 10, 2023 13:22
Show Gist options
  • Save formix/c7f38f618e88bd71dff29fc391257b2e to your computer and use it in GitHub Desktop.
Save formix/c7f38f618e88bd71dff29fc391257b2e to your computer and use it in GitHub Desktop.
Javascript circuit breaker function wrapper
/**
* Circuit breaker function wrapper.
*
* @param {*} afn An async function.
* @param {*} retries Number of retries before tripping the breaker.
* @param {*} delay Time in ms to wait before calling 'afn' again.
* @returns An async function wrapper around 'afn'.
*/
function cb(afn, retries = 3, delay = 1000) {
let tripped = false;
let fname = afn.toString().substring(0, 100).replace(/\s+/, " ").split("{")[0].trim();
return async function(...params) {
if (tripped) return;
let retry = 0;
while (retry < retries) {
try {
if (retry > 0) await sleep(delay);
return await afn(...params);
}
catch (err) {
retry++;
console.warn(
`BREAKER (${retry}/${retries}): '${fname}' | ${err.message}`);
}
}
tripped = true;
console.error(`BREAKER TRIPPED: '${fname}'`);
}
}
async function sleep(ms) {
return new Promise(r => setTimeout(r, ms));
}
module.exports = cb;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment