使用Lifecycle回调权限初始化

perf/export-docx feat-RBAC-0.8
Jimmy Liow 1 year ago
parent f2177a9e8e
commit 37c3b5aa45

@ -34,7 +34,7 @@ import { ThemeContext } from '@/stores/ThemeContext'
import { usingStorage } from '@/hooks/usingStorage'
import { isNotEmpty } from '@/utils/commons'
import { appendRequestParams } from '@/utils/request'
import useAuthStore from '@/stores/Auth'
import { fireAuth } from "./utils/lifecycle"
import { PERM_ACCOUNT_MANAGEMENT, PERM_ROLE_NEW, PERM_OVERSEA, PERM_AIR_TICKET } from '@/config'
@ -42,14 +42,18 @@ import './i18n';
const { loginToken, userId } = usingStorage()
if (isNotEmpty(loginToken)) {
const initAppliction = async () => {
if (isNotEmpty(loginToken)) {
appendRequestParams('token', loginToken)
}
}
if (isNotEmpty(userId)) {
useAuthStore.getState().loadUserPermission(userId)
if (isNotEmpty(userId)) {
await fireAuth()
}
}
await initAppliction()
const router = createBrowserRouter([
{
path: "/",

@ -3,6 +3,9 @@ import { appendRequestParams, fetchJSON, postForm } from '@/utils/request'
import { HT_HOST } from "@/config"
import { loadPageSpy } from '@/pageSpy'
import { usingStorage } from '@/hooks/usingStorage'
import { devtools } from 'zustand/middleware'
import { obervseLifecycle } from '@/utils/lifecycle'
const KEY_LOGIN_TOKEN = 'G-STR:LOGIN_TOKEN'
const KEY_TRAVEL_AGENCY_ID = 'G-INT:TRAVEL_AGENCY_ID'
@ -42,7 +45,14 @@ async function fetchLastRequet() {
return errcode !== 0 ? {} : result
}
const useAuthStore = create((set, get) => ({
const useAuthStore = create(obervseLifecycle((set, get) => ({
onAuth: () => {
const { startTokenInterval, loadUserPermission } = get()
const { userId } = usingStorage()
loadUserPermission(userId)
startTokenInterval()
},
tokenInterval: null,
@ -157,6 +167,7 @@ const useAuthStore = create((set, get) => ({
}
});
},
}))
})))
export default useAuthStore

@ -0,0 +1,42 @@
const initListener = []
const authListener = []
export const onInit = (fn) => {
initListener.push(fn)
}
export const onAuth = (fn) => {
authListener.push(fn)
}
export const fireInit = async () => {
initListener.forEach(async (fn) => {
await fn()
})
}
export const fireAuth = (obj) => {
authListener.forEach(fn => fn(obj))
}
// Zustand 中间件,用于订阅前端应用的生命周期,实验阶段
export const obervseLifecycle = (fn) => (set, get, store) => {
onInit(() => {
if (store.getState().hasOwnProperty('onInit')) {
store.getState().onInit()
} else {
console.info('store has no function: onInit.')
}
})
onAuth(() => {
if (store.getState().hasOwnProperty('onAuth')) {
store.getState().onAuth()
} else {
console.info('store has no function: onAuth.')
}
})
return fn(set, get, store)
}
Loading…
Cancel
Save