53 lines
1.3 KiB
TypeScript
53 lines
1.3 KiB
TypeScript
import axios, { type AxiosRequestConfig } from "axios";
|
|
import { API_BASE_URL } from "../config/api";
|
|
import log from "../utils/logger";
|
|
|
|
export const apiClient = axios.create({
|
|
baseURL: API_BASE_URL,
|
|
timeout: 15000,
|
|
headers: {
|
|
"Content-Type": "application/json",
|
|
},
|
|
});
|
|
|
|
apiClient.interceptors.response.use(
|
|
(response) => response,
|
|
(error) => {
|
|
if (axios.isAxiosError(error)) {
|
|
const status = error.response?.status;
|
|
if (status === 401) {
|
|
log.warn("API unauthorized response", { url: error.config?.url });
|
|
} else if (status === 403) {
|
|
log.warn("API forbidden response", { url: error.config?.url });
|
|
} else if (status && status >= 500) {
|
|
log.error("API server error", error, {
|
|
status,
|
|
url: error.config?.url,
|
|
});
|
|
}
|
|
}
|
|
return Promise.reject(error);
|
|
},
|
|
);
|
|
|
|
export function withAuth(token?: string | null): AxiosRequestConfig {
|
|
if (!token) {
|
|
return {};
|
|
}
|
|
|
|
return {
|
|
headers: {
|
|
Authorization: `Bearer ${token}`,
|
|
},
|
|
};
|
|
}
|
|
|
|
// Helper to set the auth token for a request
|
|
export const setAuthToken = (token: string) => {
|
|
if (token) {
|
|
apiClient.defaults.headers.common.Authorization = `Bearer ${token}`;
|
|
} else {
|
|
delete apiClient.defaults.headers.common.Authorization;
|
|
}
|
|
};
|