Last active
February 10, 2023 13:22
-
-
Save formix/c7f38f618e88bd71dff29fc391257b2e to your computer and use it in GitHub Desktop.
Javascript circuit breaker function wrapper
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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