Skip to content

Instantly share code, notes, and snippets.

@gsoulavy
Created July 22, 2024 15:34
Show Gist options
  • Save gsoulavy/44e36b1fa2aae2d5389a97be1fd03517 to your computer and use it in GitHub Desktop.
Save gsoulavy/44e36b1fa2aae2d5389a97be1fd03517 to your computer and use it in GitHub Desktop.
// 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