api call retry

This commit is contained in:
kosukesuenaga 2025-12-08 14:22:40 +09:00
parent c004f6c34f
commit bb072cc91c
11 changed files with 126 additions and 23 deletions

View file

@ -1,6 +1,8 @@
import { Response } from "express";
import z from "zod";
import { ERROR_DEFINITIONS, ErrorKey } from "../stores/errorCodes";
import { Delay } from "cerceis-lib";
import { MAX_RETRY_COUNT, ROOP_DELAY_MS } from "../../serverConfig";
const CustomErrorSchema = z.object({
code: z.string(),
@ -27,3 +29,18 @@ export const responseError = (error: any, res: Response | null = null) => {
if(res) return res.status(parsedError.statusCode).send(parsedError.message);
}
export const callFunctionWithRetry = async <T>(fn: () => Promise<T>): Promise<T | null> => {
for(let retryCount = 0; retryCount <= MAX_RETRY_COUNT; retryCount++) {
try {
const result = await fn();
if(!result) throw Error();
return result;
} catch(error) {
if(retryCount === MAX_RETRY_COUNT) return null;
console.warn(`\n\n========== リトライ${retryCount + 1}回目 ==========\n\n`);
await Delay(ROOP_DELAY_MS);
}
}
return null;
};