Files
tehran_taj/apps/admin-panel/src/api/client.ts
T

75 lines
2.2 KiB
TypeScript
Raw Normal View History

// Ported from legacy henza_admin/src/axios.js.
//
// Legacy pointed at the live PHP backend:
// baseURL = 'https://henzagold.com/oapi/admin/'
// The new backend is the local NestJS API. Legacy endpoint names are translated
// to clean REST paths by ./endpoints.ts — see the mapping-layer note there.
import axios from 'axios';
import { tokenName } from '../utils';
import { mapEndpoint } from './endpoints';
2026-09-09 06:46:27 +03:30
export const baseURL = import.meta.env.VITE_API_BASE_URL ?? '/api/';
2026-09-09 06:46:27 +03:30
const headers: Record<string, string> = {
'Content-Type': 'application/json',
Accept: 'application/json',
2026-09-09 06:46:27 +03:30
};
const initialToken = localStorage.getItem(tokenName);
if (initialToken) {
headers['Authorization'] = 'Bearer ' + initialToken;
}
const ax = axios.create({
baseURL,
headers,
});
/**
* Legacy re-set the auth header on every request so a token acquired after boot
* was picked up without recreating the instance. Kept — plus the endpoint
* rewrite, and without legacy's habit of sending a literal "Bearer null" when
* no token existed.
*/
ax.interceptors.request.use(
(config) => {
if (config.url) {
config.url = mapEndpoint(config.url);
}
const token = localStorage.getItem(tokenName);
if (token) {
config.headers['Authorization'] = 'Bearer ' + token;
} else {
delete config.headers['Authorization'];
}
return config;
},
(error) => Promise.reject(error),
);
/**
* NOT IN LEGACY: legacy had no response interceptor at all, so an expired token
* produced a silent failure on every subsequent call with no path back to login.
* A 401 now clears the stale session and redirects once.
*
* The redirect is a hard location assignment rather than a router push, to avoid
* importing the router here (circular: router -> stores -> client -> router).
*/
let redirecting = false;
ax.interceptors.response.use(
(response) => response,
(error) => {
if (error?.response?.status === 401 && !redirecting) {
const onLoginPage = window.location.pathname.endsWith('/auth/login');
if (!onLoginPage) {
redirecting = true;
localStorage.removeItem(tokenName);
window.location.assign(`${import.meta.env.BASE_URL}auth/login`);
}
}
return Promise.reject(error);
},
);
export default ax;