74 lines
1.8 KiB
TypeScript
74 lines
1.8 KiB
TypeScript
import axios, { AxiosError, AxiosResponse } from "axios";
|
|
import { useAuthStore } from "../features/auth/store";
|
|
|
|
const API_URL = import.meta.env.VITE_API_URL || "http://localhost:8000/api";
|
|
|
|
// Buat instance axios
|
|
export const apiClient = axios.create({
|
|
baseURL: API_URL,
|
|
headers: {
|
|
"Content-Type": "application/json",
|
|
},
|
|
});
|
|
|
|
// Interceptor untuk request
|
|
apiClient.interceptors.request.use(
|
|
(config) => {
|
|
const token = useAuthStore.getState().token;
|
|
if (token) {
|
|
config.headers.Authorization = `Bearer ${token}`
|
|
}
|
|
return config;
|
|
}, (error: AxiosError) => {
|
|
return Promise.reject(error);
|
|
}
|
|
);
|
|
|
|
// Interceptor untuk response
|
|
apiClient.interceptors.response.use(
|
|
(response: AxiosResponse) => {
|
|
return response;
|
|
},
|
|
(error: AxiosError) => {
|
|
// const { response } = error;
|
|
|
|
// Handle expired token atau unauthorized
|
|
// if (response?.status === 401) {
|
|
// useAuthStore.getState().logout();
|
|
// window.location.href = "/login";
|
|
// }
|
|
|
|
return Promise.reject(error);
|
|
}
|
|
);
|
|
|
|
// Tipe untuk respon API berdasarkan format yang Anda berikan
|
|
export interface ApiResponse<T> {
|
|
status: {
|
|
errors?: Record<string, string>;
|
|
code: number;
|
|
description: string;
|
|
};
|
|
data: T | null;
|
|
}
|
|
|
|
// Helper untuk ekstrak error dari respon API
|
|
export const extractApiErrors = (error: unknown): Record<string, string> => {
|
|
if (axios.isAxiosError(error)) {
|
|
if (error.response) {
|
|
|
|
const responseData = error.response?.data as ApiResponse<unknown>;
|
|
|
|
return (
|
|
responseData?.status?.errors || {
|
|
general: responseData?.status?.description || "Terjadi kesalahan pada server",
|
|
}
|
|
);
|
|
} else {
|
|
return { general: error.message };
|
|
}
|
|
}
|
|
|
|
return { general: "Terjadi kesalahan" };
|
|
};
|