Rearranged import orders for better visibility and readability. Also, cleaned up some of the typescript and JSX by adding appropriate line breaks and spaces, and ensuring the use of semicolons for better punctuation.
84 lines
2.2 KiB
TypeScript
84 lines
2.2 KiB
TypeScript
"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" ? window.localStorage.getItem("sub") : "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<ReqT, ResT>(
|
|
route: string,
|
|
body: ReqT,
|
|
): Promise<AxiosResponse<ResT>> {
|
|
return await axios.post(baseUrl + route, body, AxiosConfigs.authenticated.json());
|
|
}
|
|
|
|
async function doAuthenticatedGetReq<ResT>(route: string): Promise<AxiosResponse<ResT>> {
|
|
return await axios.get(baseUrl + route, AxiosConfigs.authenticated.json());
|
|
}
|
|
|
|
async function doAuthenticatedPatchReq<ReqT, ResT>(
|
|
route: string,
|
|
body: ReqT,
|
|
): Promise<AxiosResponse<ResT>> {
|
|
return await axios.patch(baseUrl + route, body, AxiosConfigs.authenticated.json());
|
|
}
|
|
|
|
async function doAuthenticatedDelReq<ResT>(route: string): Promise<AxiosResponse<ResT>> {
|
|
return await axios.delete(baseUrl + route, AxiosConfigs.authenticated.json());
|
|
}
|
|
|
|
//TODO form/multipart req
|
|
|
|
async function doJsonPostReq<ReqT, ResT>(
|
|
route: string,
|
|
body: ReqT,
|
|
): Promise<AxiosResponse<ResT>> {
|
|
return await axios.post(baseUrl + route, body, AxiosConfigs.standard.json());
|
|
}
|
|
|
|
async function doJsonGetReq<ResT>(route: string): Promise<AxiosResponse<ResT>> {
|
|
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;
|