diff --git a/src/utils/baseHttpService.ts b/src/utils/baseHttpService.ts new file mode 100644 index 0000000..789c364 --- /dev/null +++ b/src/utils/baseHttpService.ts @@ -0,0 +1,170 @@ +import axios, { AxiosRequestConfig, AxiosResponse } from "axios"; +import { API_GATE_WAY, REQUEST_TIMEOUT } from "@/constant/routes"; +import { getAuth } from "@/pages/auth"; +import { pageSize } from "@/constant/generalVariables"; +import Cookies from "js-cookie"; +import { postLogout } from "@/pages/auth/core/_requests"; +const baseURL = API_GATE_WAY; +axios.defaults.baseURL = API_GATE_WAY; +axios.defaults.timeout = REQUEST_TIMEOUT; +axios.defaults.withCredentials = true; + +const api = axios.create({ + baseURL, + withCredentials: true, + headers: { + "Content-Type": "application/json", + }, +}); + +type HttpMethod = + | "get" + | "delete" + | "head" + | "options" + | "post" + | "put" + | "patch" + | "purge" + | "link" + | "unlink"; + +type RequestConfig = Exclude; + +export const httpGetRequest = (endpoint: string, config?: RequestConfig) => + api({ + method: "get", + url: endpoint, + ...config, + }); + +export const httpPostRequest = ( + endpoint: string, + data: any, + config?: RequestConfig +) => + api({ + method: "post", + url: endpoint, + data, + ...config, + }); + +export const httpPutRequest = ( + endpoint: string, + data: any, + config?: RequestConfig +) => + api({ + method: "put", + url: endpoint, + data, + ...config, + }); + +export const httpPatchRequest = ( + endpoint: string, + data: any, + config?: RequestConfig +) => + api({ + method: "patch", + url: endpoint, + data, + ...config, + }); + +export const httpDeleteRequest = ( + endpoint: string, + config?: RequestConfig +) => + api({ + method: "delete", + url: endpoint, + ...config, + }); + +export const httpCustomRequest = ( + url: string, + method: HttpMethod, + data?: any, + config?: RequestConfig +) => + api({ + method, + url, + data, + ...config, + }); + +export const httpUploader = async (url: string, files: File[]) => { + const formData = new FormData(); + files.forEach((file) => { + formData.append("files", file, file.name); + }); + + const response = await httpPostRequest(url, formData, { + headers: { + Accept: "text/plain", + "Content-Type": "multipart/form-data", + }, + }); + + return response.data; +}; + +api.interceptors.request.use(async (config) => { + const auth = await getAuth(); + if (auth?.token) { + config.headers.Authorization = `Bearer ${auth.token}`; + } + return config; +}); + +api.interceptors.response.use( + (response) => response, + (error) => { + const num = error.response.status; + console.log("object"); + Cookies.remove("jwtToken"); + if ((num === 401 || num === 403) && location.pathname !== "/auth") { + postLogout(); + window.location.replace(import.meta.env.VITE_APP_BASE_URL + "auth"); + } else { + throw { ...error, message: error.response.data.title }; + } + } +); + +export const calculateTotalPages = (totalItemsCount: number | undefined) => { + return totalItemsCount && pageSize + ? Math.ceil(totalItemsCount / pageSize) + : 1; +}; + +export function APIUrlGenerator( + route: string, + qry?: Record, + baseUrl?: string +): string { + const query = qry || {}; + const queryKeys = Object.keys(query); + let apiUrl = `${ + baseUrl ? baseUrl : import.meta.env.VITE_APP_BACKEND_BASE_URL + }/${route}`; + queryKeys.forEach((item, index) => { + if (index === 0) { + apiUrl += "?"; + } + if ( + query[item] !== null && + query[item] !== undefined && + query[item] !== "" + ) { + apiUrl += `${item}=${query[item]}${ + index < queryKeys.length - 1 ? "&" : "" + }`; + } + }); + return apiUrl; +}