33 lines
871 B
TypeScript
33 lines
871 B
TypeScript
|
|
// Centralised axios client for the admin API.
|
||
|
|
//
|
||
|
|
// All requests carry the admin JWT (when present) from localStorage. A 401
|
||
|
|
// response clears the token and bounces to /login so the rest of the app can
|
||
|
|
// assume an authenticated session.
|
||
|
|
import axios from 'axios'
|
||
|
|
|
||
|
|
export const TOKEN_KEY = 'ca_admin_token'
|
||
|
|
|
||
|
|
const client = axios.create({
|
||
|
|
baseURL: import.meta.env.VITE_API_BASE || '/admin',
|
||
|
|
timeout: 30000,
|
||
|
|
})
|
||
|
|
|
||
|
|
client.interceptors.request.use((config) => {
|
||
|
|
const token = localStorage.getItem(TOKEN_KEY)
|
||
|
|
if (token) config.headers.Authorization = `Bearer ${token}`
|
||
|
|
return config
|
||
|
|
})
|
||
|
|
|
||
|
|
client.interceptors.response.use(
|
||
|
|
(res) => res,
|
||
|
|
(err) => {
|
||
|
|
if (err?.response?.status === 401) {
|
||
|
|
localStorage.removeItem(TOKEN_KEY)
|
||
|
|
if (location.pathname !== '/login') location.href = '/login'
|
||
|
|
}
|
||
|
|
return Promise.reject(err)
|
||
|
|
},
|
||
|
|
)
|
||
|
|
|
||
|
|
export default client
|