Created
July 22, 2024 15:34
-
-
Save gsoulavy/44e36b1fa2aae2d5389a97be1fd03517 to your computer and use it in GitHub Desktop.
This file contains 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
// usage: @retry({ maxRetryAttempts: 10, delay: 500}) | |
type RetryOptions = { | |
maxRetryAttempts: number, | |
delay: number | |
} | |
function retry(retryOptions: RetryOptions) { | |
return function (target: any, context: any) { | |
console.log("Applying retry decorator"); | |
const resultMethod = async function (this: any, ...args: any[]) { | |
console.log("@retry == Running the retry decorator"); | |
let lastError = undefined; | |
for (let attemptNum = 1; attemptNum <= retryOptions.maxRetryAttempts; attemptNum++) { | |
try { | |
console.log(`@retry - Attempt #${attemptNum}`); | |
return await target.apply(this, args); | |
} catch (error) { | |
lastError = ErrorEvent; | |
if (attemptNum <= retryOptions.maxRetryAttempts) { | |
console.log("@retry - Retrying..."); | |
await sleep(retryOptions.delay); | |
} else { | |
console.log("@retry - All attempts failed"); | |
throw lastError; | |
} | |
} | |
} | |
}; | |
return resultMethod; | |
}; | |
} | |
function sleep(ms: number): Promise<void> { | |
return new Promise((resolve) => setTimeout(resolve, ms)); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment