fix the api to handle the token expire things
This commit is contained in:
parent
abb8bcc9e4
commit
45a0222a0a
|
|
@ -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}`);
|
||||
}
|
||||
|
|
|
|||
Loading…
Reference in New Issue
Block a user