chore: initial commit
This commit is contained in:
64
src/store/index.ts
Normal file
64
src/store/index.ts
Normal file
@@ -0,0 +1,64 @@
|
||||
import { create } from 'zustand'
|
||||
|
||||
import { getSysUserInfo, logout } from '@/api'
|
||||
import { getExpandedMenus, sleep } from '@/lib'
|
||||
import type { SysUserInfo } from '@/schemas'
|
||||
|
||||
interface Store {
|
||||
token: string | null
|
||||
tokenExp: string | null
|
||||
userInfo: SysUserInfo | null
|
||||
expandedMenus: number[]
|
||||
setToken: (token: string | null, tokenExp?: string | null) => void
|
||||
logout: () => void
|
||||
init: () => Promise<void>
|
||||
toggleMenu: (id: number) => void
|
||||
}
|
||||
|
||||
const isLoginPage = () => {
|
||||
return typeof window !== 'undefined' && window.location.pathname === '/login'
|
||||
}
|
||||
|
||||
export const useStore = create<Store>((set) => {
|
||||
return {
|
||||
token: null,
|
||||
tokenExp: null,
|
||||
userInfo: null,
|
||||
expandedMenus: [],
|
||||
setToken: (token, tokenExp = null) => {
|
||||
set({ token, tokenExp })
|
||||
},
|
||||
logout: async () => {
|
||||
await logout()
|
||||
set({ token: null, tokenExp: null, userInfo: null })
|
||||
location.href = '/login'
|
||||
},
|
||||
init: async () => {
|
||||
if (isLoginPage()) {
|
||||
return
|
||||
}
|
||||
|
||||
try {
|
||||
const [{ data }] = await Promise.all([getSysUserInfo(), sleep(500)])
|
||||
set({
|
||||
userInfo: data,
|
||||
expandedMenus: getExpandedMenus(data.menus),
|
||||
})
|
||||
} catch (error) {
|
||||
console.error(error)
|
||||
set({
|
||||
userInfo: null,
|
||||
expandedMenus: [],
|
||||
})
|
||||
}
|
||||
},
|
||||
toggleMenu: (id: number) => {
|
||||
set((state) => {
|
||||
const expandedMenus = state.expandedMenus.includes(id)
|
||||
? state.expandedMenus.filter((item) => item !== id)
|
||||
: [...state.expandedMenus, id]
|
||||
return { expandedMenus }
|
||||
})
|
||||
},
|
||||
}
|
||||
})
|
||||
Reference in New Issue
Block a user