54 lines
1.4 KiB
TypeScript
54 lines
1.4 KiB
TypeScript
/** 令牌与本地缓存的读写集中在此,避免 request/auth 相互引用造成循环依赖。 */
|
|
|
|
const KEY_ACCESS = 'ttstd_access_token'
|
|
const KEY_REFRESH = 'ttstd_refresh_token'
|
|
const KEY_PROFILE = 'ttstd_profile'
|
|
const KEY_DEVICE = 'ttstd_device_sn'
|
|
|
|
export interface TokenPair {
|
|
accessToken: string
|
|
refreshToken?: string
|
|
}
|
|
|
|
export function getAccessToken(): string {
|
|
return wx.getStorageSync<string>(KEY_ACCESS) || ''
|
|
}
|
|
|
|
export function getRefreshToken(): string {
|
|
return wx.getStorageSync<string>(KEY_REFRESH) || ''
|
|
}
|
|
|
|
export function saveTokens(pair: TokenPair): void {
|
|
wx.setStorageSync(KEY_ACCESS, pair.accessToken)
|
|
if (pair.refreshToken) {
|
|
wx.setStorageSync(KEY_REFRESH, pair.refreshToken)
|
|
}
|
|
}
|
|
|
|
export function clearAuth(): void {
|
|
wx.removeStorageSync(KEY_ACCESS)
|
|
wx.removeStorageSync(KEY_REFRESH)
|
|
wx.removeStorageSync(KEY_PROFILE)
|
|
}
|
|
|
|
export function isLoggedIn(): boolean {
|
|
return !!getAccessToken()
|
|
}
|
|
|
|
export function saveProfile(profile: unknown): void {
|
|
wx.setStorageSync(KEY_PROFILE, profile)
|
|
}
|
|
|
|
export function getCachedProfile<T>(): T | null {
|
|
return (wx.getStorageSync<T>(KEY_PROFILE) as T) || null
|
|
}
|
|
|
|
/** 当前选中的设备 SN;首页加载设备列表后写入,各页面统一读取 */
|
|
export function getDeviceSn(): string {
|
|
return wx.getStorageSync<string>(KEY_DEVICE) || ''
|
|
}
|
|
|
|
export function saveDeviceSn(sn: string): void {
|
|
wx.setStorageSync(KEY_DEVICE, sn)
|
|
}
|