Files
dukang/apps/mini-hq/src/lib/session.ts
T

77 lines
1.7 KiB
TypeScript

import { useEffect, useState } from 'react';
import Taro from '@tarojs/taro';
import { isLoggedIn, redirectToLogin, request } from './api';
export type HqAccount = {
id: string;
name: string;
phone: string;
adminRole: string;
status: string;
};
let cache: HqAccount | null = null;
export async function fetchHqAccount(force = false): Promise<HqAccount | null> {
if (cache && !force) return cache;
if (!isLoggedIn()) return null;
try {
cache = await request<HqAccount>('/admin/auth/me');
return cache;
} catch {
return null;
}
}
export function clearHqAccountCache() {
cache = null;
}
/** 页面级会话守卫:未登录跳登录页;返回当前 HQ 账号 */
export function useHqSession(guard = true) {
const [account, setAccount] = useState<HqAccount | null>(cache);
const [loading, setLoading] = useState(!cache);
useEffect(() => {
if (guard && !isLoggedIn()) {
redirectToLogin();
return;
}
let alive = true;
void fetchHqAccount().then((acc) => {
if (!alive) return;
setAccount(acc);
setLoading(false);
});
return () => {
alive = false;
};
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
return { account, loading };
}
export function roleLabel(role?: string): string {
switch (role) {
case 'SUPER_ADMIN':
return '超级管理员';
case 'OPS':
return '运营';
case 'FINANCE':
return '财务';
case 'SUPPORT':
return '客服';
default:
return role || '管理员';
}
}
export function navTo(url: string) {
Taro.navigateTo({ url });
}
export function switchToTab(url: string) {
Taro.switchTab({ url });
}