feat: add new composables for category, course, and authentication management.
This commit is contained in:
parent
fb4f345483
commit
8b403f906a
3 changed files with 59 additions and 12 deletions
|
|
@ -126,10 +126,17 @@ export const useAuth = () => {
|
|||
}
|
||||
}
|
||||
|
||||
// ฟังก์ชันดึงข้อมูลโปรไฟล์ผู้ใช้ล่าสุด
|
||||
const fetchUserProfile = async () => {
|
||||
if (!token.value) return
|
||||
// Shared state สำหรับเช็คว่ากำลังโหลดโปรไฟล์อยู่หรือไม่ เพื่อป้องกันการยิงซ้อน
|
||||
const isProfileLoading = useState<boolean>('auth_profile_loading', () => false)
|
||||
const isProfileLoaded = useState<boolean>('auth_profile_loaded', () => false)
|
||||
|
||||
// ฟังก์ชันดึงข้อมูลโปรไฟล์ผู้ใช้ล่าสุด
|
||||
const fetchUserProfile = async (forceRefresh = false) => {
|
||||
// ถ้าไม่มี Token หรือกำลังโหลดอยู่ หรือโหลดข้อมูลมาแล้ว (และไม่ได้สั่ง Refresh) ให้ข้าม
|
||||
if (!token.value || isProfileLoading.value) return
|
||||
if (isProfileLoaded.value && !forceRefresh) return
|
||||
|
||||
isProfileLoading.value = true
|
||||
try {
|
||||
const data = await $fetch<User>(`${API_BASE_URL}/user/me`, {
|
||||
headers: {
|
||||
|
|
@ -139,14 +146,13 @@ export const useAuth = () => {
|
|||
|
||||
if (data) {
|
||||
user.value = data
|
||||
isProfileLoaded.value = true
|
||||
}
|
||||
} catch (error: any) {
|
||||
// กรณี Token หมดอายุ (401)
|
||||
if (error.statusCode === 401) {
|
||||
// พยายามขอ Token ใหม่ (Refresh Token)
|
||||
const refreshed = await refreshAccessToken()
|
||||
if (refreshed) {
|
||||
// ถ้าได้ Token ใหม่ ให้ลองดึงข้อมูลอีกครั้ง
|
||||
try {
|
||||
const retryData = await $fetch<User>(`${API_BASE_URL}/user/me`, {
|
||||
headers: {
|
||||
|
|
@ -156,18 +162,20 @@ export const useAuth = () => {
|
|||
|
||||
if (retryData) {
|
||||
user.value = retryData
|
||||
isProfileLoaded.value = true
|
||||
return
|
||||
}
|
||||
} catch (retryErr) {
|
||||
console.error('Failed to fetch user profile after refresh:', retryErr)
|
||||
}
|
||||
} else {
|
||||
// ถ้า Refresh ไม่ผ่าน ให้ Logout
|
||||
logout()
|
||||
}
|
||||
} else {
|
||||
console.error('Failed to fetch user profile:', error)
|
||||
}
|
||||
} finally {
|
||||
isProfileLoading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue