"use client"; import axios, { type AxiosResponse } from "axios"; const baseUrl = process.env.NEXT_PUBLIC_API_URL || "http://localhost:3333/"; const AxiosConfigs = { authenticated: { json: () => { return { headers: { "content-type": "application/json", Authorization: `Bearer ${typeof window !== "undefined" ? JSON.parse(window.localStorage.getItem("sub") || "not-ssr") : "not-ssr"}`, }, validateStatus: (status: number) => { return status < 500; // Resolve only if the status code is less than 500 }, }; }, }, standard: { json: () => { return { headers: { "content-type": "application/json", }, validateStatus: (status: number) => { return status < 500; // Resolve only if the status code is less than 500 }, }; }, }, }; async function doAuthenticatedJsonPostReq( route: string, body: ReqT, ): Promise> { return await axios.post(baseUrl + route, body, AxiosConfigs.authenticated.json()); } async function doAuthenticatedGetReq(route: string): Promise> { return await axios.get(baseUrl + route, AxiosConfigs.authenticated.json()); } async function doAuthenticatedPatchReq( route: string, body: ReqT, ): Promise> { return await axios.patch(baseUrl + route, body, AxiosConfigs.authenticated.json()); } async function doAuthenticatedDelReq(route: string): Promise> { return await axios.delete(baseUrl + route, AxiosConfigs.authenticated.json()); } //TODO form/multipart req async function doJsonPostReq( route: string, body: ReqT, ): Promise> { return await axios.post(baseUrl + route, body, AxiosConfigs.standard.json()); } async function doJsonGetReq(route: string): Promise> { return await axios.get(baseUrl + route, AxiosConfigs.standard.json()); } const ApiRequest = { authenticated: { post: { json: doAuthenticatedJsonPostReq }, patch: { json: doAuthenticatedPatchReq }, delete: { json: doAuthenticatedDelReq }, get: { json: doAuthenticatedGetReq }, }, standard: { post: { json: doJsonPostReq }, get: { json: doJsonGetReq }, }, }; export default ApiRequest;