37 lines
1.0 KiB
TypeScript
37 lines
1.0 KiB
TypeScript
import axios from "axios";
|
|
import { getAuthToken } from "./auth";
|
|
import { clearAuthToken } from "./auth";
|
|
|
|
const envBaseUrl = process.env.REACT_APP_API_BASE_URL;
|
|
const defaultBaseUrl =
|
|
window.location.hostname === "localhost"
|
|
? "http://localhost:5202/api"
|
|
: "/api";
|
|
|
|
export const api = axios.create({
|
|
baseURL: envBaseUrl && envBaseUrl.trim().length > 0 ? envBaseUrl : defaultBaseUrl,
|
|
});
|
|
|
|
api.interceptors.request.use((config) => {
|
|
const token = getAuthToken();
|
|
if (token) {
|
|
config.headers = config.headers ?? {};
|
|
config.headers.Authorization = `Bearer ${token}`;
|
|
}
|
|
return config;
|
|
});
|
|
|
|
api.interceptors.response.use(
|
|
(r) => r,
|
|
(err) => {
|
|
// If tokens expire (Google ID tokens are short-lived), clear and let the UI prompt the user.
|
|
const status = err?.response?.status;
|
|
if (status === 401) {
|
|
clearAuthToken();
|
|
// Avoid hard navigation loops; let views handle the missing token state.
|
|
// We still reject so callers can show a toast if they want.
|
|
}
|
|
return Promise.reject(err);
|
|
},
|
|
);
|