/* eslint-disable no-underscore-dangle */ import axios, { AxiosRequestConfig } from "axios"; import { configSrore, setValue } from "../configSrore"; import { ERequest } from "../interface"; export const ClasorFileManagementAxiosInstance = axios.create(); const Fetch = async (FetchConfig: { url: string; method: ERequest; data?: { [key: string]: any; }; params?: { [key: string]: any; }; headers?: { [key: string]: string; }; disableErrorMessage?: boolean; fileRequest?:boolean; responseType?: | "arraybuffer" | "blob" | "document" | "json" | "text" | "stream"; }): Promise => { ClasorFileManagementAxiosInstance.defaults.timeout = 36_000_000; // 10min return new Promise(async (resolve, reject) => { const token = configSrore.userToken; const request: AxiosRequestConfig = { method: FetchConfig.method, url: FetchConfig.url, data: FetchConfig.data, params: FetchConfig.params, headers: { ...FetchConfig.headers, "Content-Type": FetchConfig.fileRequest ? "multipart/form-data; boundary=" : "application/json;charset=utf-8", "Accept-Language": "fa-IR,fa;q=0.9", }, responseType: FetchConfig.responseType, }; if (token && request.headers) { request.headers.Authorization = `Bearer ${token}`; request.headers._token_ = `${token}`; request.headers._token_issuer_ = "1"; } await ClasorFileManagementAxiosInstance(request) .then((res) => { resolve(res.data as T); }) .catch(async (error) => { if ( error.response && error.response.data && error.response.status === 401 && configSrore.onRefresh ) { try { const refreshResult = await configSrore.onRefresh(); // retry after refresh token if (refreshResult) { try { setValue("userToken", refreshResult); resolve(await Fetch(FetchConfig)); return; } catch (retryError) { configSrore.onError?.(retryError); reject(retryError); return; } } } catch (error_) { configSrore.onError?.(error_); } return; } configSrore.onError?.(error); reject(error); }); }); }; export default Fetch;