diff --git a/src/utils/func.ts b/src/utils/func.ts new file mode 100644 index 0000000..27b2dc5 --- /dev/null +++ b/src/utils/func.ts @@ -0,0 +1,25 @@ +const MAX_RETRY = 3; + +/** + * @param func - Function to do. + * @param cond - Retry condition callback function. Stop when the function return false, + */ +export async function retry any>( + func: T, + cond = (error: any) => !!error, +): Promise> { + let retries = 0; + + while (retries++ < MAX_RETRY - 1) { + try { + return await func(); + } catch (error) { + if (cond(error)) { + retries++; + continue; + } + throw error; + } + } + return func(); +}