feat(utils): add base HTTP service for API calls
- Add axios-based HTTP service with interceptors - Add authentication header management - Add APIUrlGenerator for dynamic URL building - Support for all HTTP methods (GET, POST, PUT, DELETE, etc.) - Error handling and automatic logout on 401/403
This commit is contained in:
parent
e5b23fdeb1
commit
0d322f1767
|
|
@ -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<AxiosRequestConfig, "method" | "url">;
|
||||||
|
|
||||||
|
export const httpGetRequest = <T>(endpoint: string, config?: RequestConfig) =>
|
||||||
|
api<T>({
|
||||||
|
method: "get",
|
||||||
|
url: endpoint,
|
||||||
|
...config,
|
||||||
|
});
|
||||||
|
|
||||||
|
export const httpPostRequest = <T>(
|
||||||
|
endpoint: string,
|
||||||
|
data: any,
|
||||||
|
config?: RequestConfig
|
||||||
|
) =>
|
||||||
|
api<T>({
|
||||||
|
method: "post",
|
||||||
|
url: endpoint,
|
||||||
|
data,
|
||||||
|
...config,
|
||||||
|
});
|
||||||
|
|
||||||
|
export const httpPutRequest = <T>(
|
||||||
|
endpoint: string,
|
||||||
|
data: any,
|
||||||
|
config?: RequestConfig
|
||||||
|
) =>
|
||||||
|
api<T>({
|
||||||
|
method: "put",
|
||||||
|
url: endpoint,
|
||||||
|
data,
|
||||||
|
...config,
|
||||||
|
});
|
||||||
|
|
||||||
|
export const httpPatchRequest = <T>(
|
||||||
|
endpoint: string,
|
||||||
|
data: any,
|
||||||
|
config?: RequestConfig
|
||||||
|
) =>
|
||||||
|
api<T>({
|
||||||
|
method: "patch",
|
||||||
|
url: endpoint,
|
||||||
|
data,
|
||||||
|
...config,
|
||||||
|
});
|
||||||
|
|
||||||
|
export const httpDeleteRequest = <T>(
|
||||||
|
endpoint: string,
|
||||||
|
config?: RequestConfig
|
||||||
|
) =>
|
||||||
|
api<T>({
|
||||||
|
method: "delete",
|
||||||
|
url: endpoint,
|
||||||
|
...config,
|
||||||
|
});
|
||||||
|
|
||||||
|
export const httpCustomRequest = <T>(
|
||||||
|
url: string,
|
||||||
|
method: HttpMethod,
|
||||||
|
data?: any,
|
||||||
|
config?: RequestConfig
|
||||||
|
) =>
|
||||||
|
api<T>({
|
||||||
|
method,
|
||||||
|
url,
|
||||||
|
data,
|
||||||
|
...config,
|
||||||
|
});
|
||||||
|
|
||||||
|
export const httpUploader = async <T>(url: string, files: File[]) => {
|
||||||
|
const formData = new FormData();
|
||||||
|
files.forEach((file) => {
|
||||||
|
formData.append("files", file, file.name);
|
||||||
|
});
|
||||||
|
|
||||||
|
const response = await httpPostRequest<T>(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<string, string | number | null>,
|
||||||
|
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;
|
||||||
|
}
|
||||||
Loading…
Reference in New Issue