690331:1616 Correspondence Page Refactor by GPT-5.3-Codex Medium #03
CI / CD Pipeline / build (push) Successful in 15m34s
CI / CD Pipeline / deploy (push) Successful in 6m11s

This commit is contained in:
2026-03-31 16:16:12 +07:00
parent 156c28f49e
commit bf5c67fc7e
4 changed files with 60 additions and 28 deletions
+52 -15
View File
@@ -5,6 +5,49 @@ import { v4 as uuidv4 } from 'uuid';
// อ่านค่า Base URL จาก Environment Variable
const baseURL = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:3001/api';
// Token cache for API calls outside React components
let cachedToken: string | null = null;
let tokenPromise: Promise<string | null> | null = null;
// Async function to get token
async function getAuthToken(): Promise<string | null> {
if (cachedToken) return cachedToken;
if (tokenPromise) return tokenPromise;
tokenPromise = (async () => {
try {
if (typeof window !== 'undefined') {
const { getSession } = await import('next-auth/react');
const session = await getSession();
cachedToken = session?.accessToken || null;
return cachedToken;
}
} catch (_error) {
// Fallback to localStorage
try {
const authStorage = localStorage.getItem('auth-storage');
if (authStorage) {
const parsed = JSON.parse(authStorage);
cachedToken = parsed?.state?.token || null;
return cachedToken;
}
} catch (__error) {
// All methods failed
}
}
return null;
})();
return tokenPromise;
}
// Function to clear token cache (call on logout)
export function clearAuthTokenCache(): void {
cachedToken = null;
tokenPromise = null;
}
// สร้าง Axios Instance หลัก
const apiClient: AxiosInstance = axios.create({
baseURL,
@@ -28,20 +71,11 @@ apiClient.interceptors.request.use(
}
// 2. Authentication Token Injection
// ดึง Token จาก Zustand persist store (localStorage)
// ดึง Token จาก NextAuth session ผ่าน getSession()
if (typeof window !== 'undefined') {
try {
const authStorage = localStorage.getItem('auth-storage');
if (authStorage) {
const parsed = JSON.parse(authStorage);
const token = parsed?.state?.token;
if (token) {
config.headers['Authorization'] = `Bearer ${token}`;
}
}
} catch (_error) {
// Auth token retrieval failed - request will proceed without token
const token = await getAuthToken();
if (token) {
config.headers['Authorization'] = `Bearer ${token}`;
}
}
@@ -66,8 +100,11 @@ apiClient.interceptors.response.use(
// กรณี Token หมดอายุ หรือ ไม่มีสิทธิ์
if (status === 401) {
// Unauthorized: redirect handled by auth interceptor
// สามารถเพิ่ม Logic Redirect ไปหน้า Login ได้ถ้าต้องการ
// Clear cached token and redirect to login
clearAuthTokenCache();
if (typeof window !== 'undefined') {
window.location.href = '/login';
}
}
}
return Promise.reject(error);