From 45a0222a0a60368f23a541ba5baea795869bcc61 Mon Sep 17 00:00:00 2001 From: saeed0920 Date: Sat, 13 Sep 2025 14:39:29 +0330 Subject: [PATCH] fix the api to handle the token expire things --- app/lib/api.ts | 31 ++++++++++++++++++++++++------- 1 file changed, 24 insertions(+), 7 deletions(-) diff --git a/app/lib/api.ts b/app/lib/api.ts index b26b23c..062c434 100644 --- a/app/lib/api.ts +++ b/app/lib/api.ts @@ -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( endpoint: string, options: RequestInit = {}, @@ -66,6 +79,11 @@ class ApiService { const response = await fetch(url, config); const data: ApiResponse = 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 = 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}`); } -- 2.46.0.windows.1