36 lines
807 B
JavaScript
36 lines
807 B
JavaScript
let onSessionExpiredCallback = null;
|
|
|
|
export const setSessionExpiredCallback = (callback) => {
|
|
onSessionExpiredCallback = callback;
|
|
};
|
|
|
|
const authFetch = async (url, options = {}) => {
|
|
const token = localStorage.getItem('token');
|
|
|
|
if (!token) {
|
|
onSessionExpiredCallback?.();
|
|
return null;
|
|
}
|
|
|
|
const method = options.method?.toUpperCase() || 'GET';
|
|
const shouldIncludeContentType = ['POST', 'PUT', 'PATCH'].includes(method);
|
|
|
|
const res = await fetch(url, {
|
|
...options,
|
|
headers: {
|
|
Authorization: `Bearer ${token}`,
|
|
...(shouldIncludeContentType && { 'Content-Type': 'application/json' }),
|
|
...options.headers,
|
|
},
|
|
});
|
|
|
|
if ([401, 403].includes(res.status)) {
|
|
onSessionExpiredCallback?.();
|
|
return null;
|
|
}
|
|
|
|
return res;
|
|
};
|
|
|
|
export default authFetch;
|