31 lines
1018 B
TypeScript
31 lines
1018 B
TypeScript
import { API_BASE_URL } from "../config/constants";
|
|
|
|
export const authFetch = async (endpoint: string, options: RequestInit = {}) => {
|
|
const token = localStorage.getItem("accessToken");
|
|
const isFormData = options.body instanceof FormData;
|
|
|
|
const headers: HeadersInit = {
|
|
...(!isFormData && { "Content-Type": "application/json" }),
|
|
...(token ? { Authorization: `Bearer ${token}` } : {}),
|
|
...options.headers,
|
|
};
|
|
|
|
// Safely join URLs preventing double slashes (e.g., "http://api.com//api/..." -> "http://api.com/api/...")
|
|
const cleanBaseUrl = API_BASE_URL.replace(/\/+$/, "");
|
|
const cleanEndpoint = endpoint.startsWith("/") ? endpoint : `/${endpoint}`;
|
|
const url = `${cleanBaseUrl}${cleanEndpoint}`;
|
|
|
|
const response = await fetch(url, {
|
|
...options,
|
|
headers,
|
|
});
|
|
|
|
if (response.status === 401) {
|
|
localStorage.removeItem("accessToken");
|
|
localStorage.removeItem("refreshToken");
|
|
window.location.href = "/login";
|
|
}
|
|
|
|
return response;
|
|
};
|