UNPKG

@0xtld/tair-node

Version:

A Node.js package for Tair functionality with configuration, core, and helper modules.

94 lines (82 loc) 2.94 kB
import axios, { AxiosInstance, AxiosRequestConfig, AxiosRequestHeaders, AxiosResponse } from 'axios'; import { CONSTANTS } from '../config/constant'; import { logger } from '../config'; interface RetryConfigs { maxAttempts: number; delay: number; } class AsyncHelper { static async retryOperation<T>(operation: () => Promise<T>, configs: RetryConfigs = { maxAttempts: CONSTANTS.RETRY_ATTEMPTS, delay: CONSTANTS.RETRY_DELAY }): Promise<T> { const { maxAttempts, delay } = configs; for (let attempt = 1; attempt <= maxAttempts; attempt++) { try { return await operation(); } catch (error) { if (attempt === maxAttempts) throw error; logger.warn(`Retry ${operation.name} failed attempt ${attempt} of ${maxAttempts}. Retrying.... in ${attempt} seconds`); await new Promise(resolve => setTimeout(resolve, delay * attempt)); } } throw new Error(`Retry operation failed after ${maxAttempts} attempts`); } } class AxiosHelper { static headers(configs?: string | AxiosRequestHeaders): AxiosRequestHeaders { let headers = { accept: "*/*", "accept-encoding": "gzip, deflate, br, zstd", "accept-language": "en-US;q=0.6,en;q=0.5", "content-type": "application/json", "sec-ch-ua": '"Chromium";v="130", "Google Chrome";v="130", "Not?A_Brand";v="99""', "sec-ch-ua-mobile": "?0", "sec-ch-ua-platform": '"Windows"', "sec-fetch-dest": "empty", "sec-fetch-mode": "cors", "sec-fetch-site": "same-origin", "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0.0.0 Safari/537.36", } as unknown as AxiosRequestHeaders; if (typeof configs === "object") { headers = { ...headers, ...configs } as AxiosRequestHeaders; } else if (typeof configs === "string") { headers["origin"] = `${configs}`; headers["referer"] = `${configs}/`; } return headers; } static createInstance(axiosConfigs: AxiosRequestConfig, configs: { isCustomInterceptors?: boolean; origin?: string | null; } = { isCustomInterceptors: false, origin: null, }): AxiosInstance { const instance = axios.create(axiosConfigs); const { isCustomInterceptors, origin } = configs; if (!isCustomInterceptors) { instance.interceptors.request.use( (config) => { if (origin) { config.headers = AxiosHelper.headers(origin); } return config; }, (error) => { return Promise.reject(error); } ); instance.interceptors.response.use( (response: AxiosResponse) => { return response.data; }, (error) => { return Promise.reject(error); } ); } // TODO: Add handle custom configurations here return instance; } } export { AsyncHelper, AxiosHelper, RetryConfigs };