fix(web): localStorage safety, default fetch timeout, visibility-aware polling

This commit is contained in:
2026-04-29 12:00:40 +08:00
parent 7377c2135f
commit 357d08f2e3
5 changed files with 210 additions and 43 deletions
+46 -8
View File
@@ -8,26 +8,64 @@ export interface User {
is_admin: boolean
}
function safeReadJSON<T>(key: string, fallback: T): T {
try {
const raw = localStorage.getItem(key)
if (raw === null) return fallback
return JSON.parse(raw) as T
} catch {
// 脏数据 / 反序列化失败 → 清掉,回退默认。
try {
localStorage.removeItem(key)
} catch {
/* noop */
}
return fallback
}
}
function safeReadString(key: string): string | null {
try {
return localStorage.getItem(key)
} catch {
return null
}
}
function safeWrite(key: string, value: string) {
try {
localStorage.setItem(key, value)
} catch {
/* QuotaExceeded / disabled */
}
}
function safeRemove(key: string) {
try {
localStorage.removeItem(key)
} catch {
/* noop */
}
}
export const useAuthStore = defineStore('auth', () => {
const token = ref<string | null>(localStorage.getItem('token'))
const user = ref<User | null>(
JSON.parse(localStorage.getItem('user') || 'null') as User | null,
)
const token = ref<string | null>(safeReadString('token'))
const user = ref<User | null>(safeReadJSON<User | null>('user', null))
const isAuthenticated = computed(() => !!token.value)
function setSession(t: string, u: User) {
token.value = t
user.value = u
localStorage.setItem('token', t)
localStorage.setItem('user', JSON.stringify(u))
safeWrite('token', t)
safeWrite('user', JSON.stringify(u))
}
function clearSession() {
token.value = null
user.value = null
localStorage.removeItem('token')
localStorage.removeItem('user')
safeRemove('token')
safeRemove('user')
}
return { token, user, isAuthenticated, setSession, clearSession }