Created
June 20, 2024 04:05
-
-
Save ali-master/ae1d9c062a5a131d614a3433f26d7e5c to your computer and use it in GitHub Desktop.
Retry Pattern in NestJS
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
import { Injectable } from '@nestjs/common'; | |
import { AxiosResponse } from 'axios'; | |
export type AxiosMethod = () => Promise<AxiosResponse>; | |
@Injectable() | |
export class Retry { | |
constructor() {} | |
async retry( | |
axiosMethod: AxiosMethod, | |
retry: number, | |
delayInMs: number, | |
jitter: boolean, | |
): Promise<AxiosResponse> { | |
try { | |
let res: AxiosResponse | null = null; | |
for (let i = 0; i <= retry; i++) { | |
try { | |
res = await axiosMethod(); | |
break; | |
} catch (err) { | |
if (i < retry) { | |
const j = this.getJitter(jitter); | |
await this.executeWithDelay(delayInMs + j); | |
continue | |
} else { | |
throw err; | |
} | |
} | |
} | |
return res; | |
} catch (error) { | |
throw error; | |
} | |
} | |
private executeWithDelay(delay: number) { | |
return new Promise((resolve) => setTimeout(resolve, delay)); | |
} | |
private getJitter(jitter: boolean) { | |
return jitter ? Math.floor(Math.random() * (200 - 50 + 1)) + 50 : 0; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment