proposal-system/web/src/lib/api/client.ts
Adam Moussa da783d48cd
Some checks failed
Deploy / Deploy to AWS (push) Waiting to run
Deploy Mobile (iOS) / Build & Upload to TestFlight (push) Has been cancelled
fix(web): restore WEB-C1/M4 fixes reverted by rebase conflict resolution
- client.ts: localStorage → sessionStorage (WEB-C1 critical fix)
- proposals.ts: re-add 'Other' to ServiceCategory (WEB-M4)
- ProposalListPage.tsx: STATUS_COLORS → STATUS_CHIP_STYLES (visual design)
2026-05-27 18:21:03 -04:00

65 lines
1.8 KiB
TypeScript

import axios from 'axios';
import { API_URL, STORAGE_KEY_TOKEN } from '../../constants';
import { store } from '../../app/store';
import { logout } from '../../app/slices/authSlice';
const apiClient = axios.create({
baseURL: API_URL,
headers: {
'Content-Type': 'application/json',
Accept: 'application/json',
},
});
apiClient.interceptors.request.use(
(config) => {
const tokenData = window.sessionStorage.getItem(STORAGE_KEY_TOKEN);
if (tokenData) {
try {
const parsed = JSON.parse(tokenData);
if (parsed?.token) {
config.headers.Authorization = `Bearer ${parsed.token}`;
}
} catch {
// Invalid token data
}
}
return config;
},
(error) => Promise.reject(error)
);
apiClient.interceptors.response.use(
(response) => response,
(error) => {
if (error.response) {
const { status, data } = error.response;
if (status === 401) {
// Fix: WEB-M2 — dispatch Redux logout to clear auth state in addition to storage
store.dispatch(logout());
window.location.href = '/login';
return Promise.reject(new Error('Session expired. Please log in again.'));
}
if (status === 403) {
return Promise.reject(new Error('You do not have permission to perform this action.'));
}
if (status === 404) {
return Promise.reject(new Error('The requested resource was not found.'));
}
const message = data?.detail || data?.title || data?.message || 'An error occurred';
return Promise.reject(new Error(message));
}
if (error.request) {
return Promise.reject(new Error('No response from server. Please check your connection.'));
}
return Promise.reject(error);
}
);
export default apiClient;