2025-08-05 12:35:40 +07:00
|
|
|
import axios from 'axios'
|
2025-08-14 03:09:00 +07:00
|
|
|
import { toast } from 'react-toastify'
|
2025-08-05 12:35:40 +07:00
|
|
|
|
|
|
|
|
const getToken = () => {
|
|
|
|
|
return localStorage.getItem('authToken')
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
export const api = axios.create({
|
|
|
|
|
baseURL: process.env.NEXT_PUBLIC_API_URL,
|
|
|
|
|
headers: {
|
|
|
|
|
'Content-Type': 'application/json'
|
|
|
|
|
},
|
|
|
|
|
timeout: 10000
|
|
|
|
|
})
|
|
|
|
|
|
|
|
|
|
api.interceptors.request.use(
|
|
|
|
|
config => {
|
|
|
|
|
const token = getToken()
|
|
|
|
|
if (token) {
|
|
|
|
|
config.headers.Authorization = `Bearer ${token}`
|
|
|
|
|
}
|
|
|
|
|
return config
|
|
|
|
|
},
|
|
|
|
|
error => {
|
|
|
|
|
return Promise.reject(error)
|
|
|
|
|
}
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
api.interceptors.response.use(
|
|
|
|
|
response => response,
|
|
|
|
|
error => {
|
|
|
|
|
const status = error.response?.status
|
2025-08-14 00:29:19 +07:00
|
|
|
const currentPath = window.location.pathname
|
2025-08-05 12:35:40 +07:00
|
|
|
|
2025-08-14 00:29:19 +07:00
|
|
|
if (status === 401 && !currentPath.endsWith('/login')) {
|
2025-08-05 12:35:40 +07:00
|
|
|
window.location.href = '/login'
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if (status === 403) {
|
|
|
|
|
console.error('Forbidden: Kamu tidak punya akses.')
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if (status >= 500) {
|
2025-08-14 03:09:00 +07:00
|
|
|
toast.error(error.response?.data?.errors[0].cause || 'Terjadi kesalahan server.')
|
2025-08-05 12:35:40 +07:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return Promise.reject(error)
|
|
|
|
|
}
|
|
|
|
|
)
|
2025-08-14 00:29:19 +07:00
|
|
|
|