fix the api to handle the token expire things (#11)

fix the api token expire time!

Reviewed-on: https://git.pelekan.org/Saeed0920/inogen/pulls/11
Co-authored-by: saeed0920 <sd.eed1381@gmail.com>
Co-committed-by: saeed0920 <sd.eed1381@gmail.com>
This commit is contained in:
Saeed AB 2025-09-16 22:08:39 +03:30 committed by Saeed AB
parent e3431533ca
commit 137882fcb3

View File

@ -39,6 +39,19 @@ class ApiService {
this.token = null;
}
private handleSessionExpired(message?: string) {
this.clearToken();
localStorage.removeItem("auth_token");
localStorage.removeItem("auth_user");
try {
sessionStorage.setItem("sessionExpired", "1");
} catch {}
if (message) {
toast.error(message);
}
window.location.href = "/login";
}
private async request<T = any>(
endpoint: string,
options: RequestInit = {},
@ -66,6 +79,11 @@ class ApiService {
const response = await fetch(url, config);
const data: ApiResponse<T> = await response.json();
if (data.errorCode === 301) {
this.handleSessionExpired("نشست شما منقضی شده است. لطفا دوباره وارد شوید.");
throw new Error(data.message || "Session expired");
}
// Handle different response states
if (!response.ok) {
throw new Error(
@ -91,13 +109,7 @@ class ApiService {
// Handle authentication errors
if (error instanceof Error && error.message.includes("401")) {
this.clearToken();
localStorage.removeItem("auth_token");
localStorage.removeItem("auth_user");
try {
sessionStorage.setItem("sessionExpired", "1");
} catch {}
window.location.href = "/login";
this.handleSessionExpired();
throw error;
}
@ -128,6 +140,11 @@ class ApiService {
const response = await fetch(fullUrl, config);
const apiData: ApiResponse<T> = await response.json();
if (apiData.errorCode === 301) {
this.handleSessionExpired("نشست شما منقضی شده است. لطفا دوباره وارد شوید.");
throw new Error(apiData.message || "Session expired");
}
if (!response.ok) {
throw new Error(apiData?.message || `HTTP error! status: ${response.status}`);
}