refactor: Separate store

This commit is contained in:
vben
2024-07-30 21:10:28 +08:00
parent cf0ec053e4
commit 89dcf522f5
40 changed files with 338 additions and 345 deletions

View File

@@ -1,15 +1,15 @@
import { createPinia, setActivePinia } from 'pinia';
import { beforeEach, describe, expect, it } from 'vitest';
import { useCoreAccessStore } from './access';
import { useAccessStore } from './access';
describe('useCoreAccessStore', () => {
describe('useAccessStore', () => {
beforeEach(() => {
setActivePinia(createPinia());
});
it('updates accessMenus state', () => {
const store = useCoreAccessStore();
const store = useAccessStore();
expect(store.accessMenus).toEqual([]);
store.setAccessMenus([{ name: 'Dashboard', path: '/dashboard' }]);
expect(store.accessMenus).toEqual([
@@ -17,68 +17,29 @@ describe('useCoreAccessStore', () => {
]);
});
it('updates userInfo and userRoles state', () => {
const store = useCoreAccessStore();
expect(store.userInfo).toBeNull();
expect(store.userRoles).toEqual([]);
const userInfo: any = { name: 'John Doe', roles: ['admin'] };
store.setUserInfo(userInfo);
expect(store.userInfo).toEqual(userInfo);
expect(store.userRoles).toEqual(['admin']);
});
it('returns correct userInfo', () => {
const store = useCoreAccessStore();
const userInfo: any = { name: 'Jane Doe', roles: [{ value: 'user' }] };
store.setUserInfo(userInfo);
expect(store.userInfo).toEqual(userInfo);
});
it('updates accessToken state correctly', () => {
const store = useCoreAccessStore();
const store = useAccessStore();
expect(store.accessToken).toBeNull(); // 初始状态
store.setAccessToken('abc123');
expect(store.accessToken).toBe('abc123');
});
// 测试重置用户信息时的行为
it('clears userInfo and userRoles when setting null userInfo', () => {
const store = useCoreAccessStore();
store.setUserInfo({
roles: [{ roleName: 'User', value: 'user' }],
} as any);
expect(store.userInfo).not.toBeNull();
expect(store.userRoles.length).toBeGreaterThan(0);
store.setUserInfo(null as any); // 重置用户信息
expect(store.userInfo).toBeNull();
expect(store.userRoles).toEqual([]);
});
it('returns the correct accessToken', () => {
const store = useCoreAccessStore();
const store = useAccessStore();
store.setAccessToken('xyz789');
expect(store.accessToken).toBe('xyz789');
});
// 测试在没有用户角色时返回空数组
it('returns an empty array for userRoles if not set', () => {
const store = useCoreAccessStore();
expect(store.userRoles).toEqual([]);
});
// 测试设置空的访问菜单列表
it('handles empty accessMenus correctly', () => {
const store = useCoreAccessStore();
const store = useAccessStore();
store.setAccessMenus([]);
expect(store.accessMenus).toEqual([]);
});
// 测试设置空的访问路由列表
it('handles empty accessRoutes correctly', () => {
const store = useCoreAccessStore();
const store = useAccessStore();
store.setAccessRoutes([]);
expect(store.accessRoutes).toEqual([]);
});

View File

@@ -5,29 +5,6 @@ import { acceptHMRUpdate, defineStore } from 'pinia';
type AccessToken = null | string;
interface BasicUserInfo {
/**
* 头像
*/
avatar: string;
/**
* 用户昵称
*/
realName: string;
/**
* 用户角色
*/
roles?: string[];
/**
* 用户id
*/
userId: string;
/**
* 用户名
*/
username: string;
}
interface AccessState {
/**
* 权限码
@@ -45,24 +22,20 @@ interface AccessState {
* 登录 accessToken
*/
accessToken: AccessToken;
/**
* 登录是否过期
*/
loginExpired: boolean;
/**
* 登录 accessToken
*/
refreshToken: AccessToken;
/**
* 用户信息
*/
userInfo: BasicUserInfo | null;
/**
* 用户角色
*/
userRoles: string[];
}
/**
* @zh_CN 访问权限相关
*/
export const useCoreAccessStore = defineStore('core-access', {
export const useAccessStore = defineStore('core-access', {
actions: {
setAccessCodes(codes: string[]) {
this.accessCodes = codes;
@@ -76,19 +49,12 @@ export const useCoreAccessStore = defineStore('core-access', {
setAccessToken(token: AccessToken) {
this.accessToken = token;
},
setLoginExpired(loginExpired: boolean) {
this.loginExpired = loginExpired;
},
setRefreshToken(token: AccessToken) {
this.refreshToken = token;
},
setUserInfo(userInfo: BasicUserInfo | null) {
// 设置用户信息
this.userInfo = userInfo;
// 设置角色信息
const roles = userInfo?.roles ?? [];
this.setUserRoles(roles);
},
setUserRoles(roles: string[]) {
this.userRoles = roles;
},
},
persist: {
// 持久化
@@ -99,14 +65,13 @@ export const useCoreAccessStore = defineStore('core-access', {
accessMenus: [],
accessRoutes: [],
accessToken: null,
loginExpired: false,
refreshToken: null,
userInfo: null,
userRoles: [],
}),
});
// 解决热更新问题
const hot = import.meta.hot;
if (hot) {
hot.accept(acceptHMRUpdate(useCoreAccessStore, hot));
hot.accept(acceptHMRUpdate(useAccessStore, hot));
}

View File

@@ -1,3 +1,4 @@
export * from './access';
export * from './lock';
export * from './tabbar';
export * from './user';

View File

@@ -1,29 +1,29 @@
import { createPinia, setActivePinia } from 'pinia';
import { beforeEach, describe, expect, it } from 'vitest';
import { useCoreLockStore } from './lock';
import { useLockStore } from './lock';
describe('useCoreLockStore', () => {
describe('useLockStore', () => {
beforeEach(() => {
// 每个测试前重置 Pinia
setActivePinia(createPinia());
});
it('should initialize with correct default state', () => {
const store = useCoreLockStore();
const store = useLockStore();
expect(store.isLockScreen).toBe(false);
expect(store.lockScreenPassword).toBeUndefined();
});
it('should lock screen with a password', () => {
const store = useCoreLockStore();
const store = useLockStore();
store.lockScreen('1234');
expect(store.isLockScreen).toBe(true);
expect(store.lockScreenPassword).toBe('1234');
});
it('should unlock screen and clear password', () => {
const store = useCoreLockStore();
const store = useLockStore();
store.lockScreen('1234');
store.unlockScreen();
expect(store.isLockScreen).toBe(false);

View File

@@ -11,7 +11,7 @@ interface AppState {
lockScreenPassword?: string;
}
export const useCoreLockStore = defineStore('core-lock', {
export const useLockStore = defineStore('core-lock', {
actions: {
lockScreen(password: string) {
this.isLockScreen = true;

View File

@@ -3,9 +3,9 @@ import { createRouter, createWebHistory } from 'vue-router';
import { createPinia, setActivePinia } from 'pinia';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { useCoreTabbarStore } from './tabbar';
import { useTabbarStore } from './tabbar';
describe('useCoreAccessStore', () => {
describe('useAccessStore', () => {
const router = createRouter({
history: createWebHistory(),
routes: [],
@@ -18,7 +18,7 @@ describe('useCoreAccessStore', () => {
});
it('adds a new tab', () => {
const store = useCoreTabbarStore();
const store = useTabbarStore();
const tab: any = {
fullPath: '/home',
meta: {},
@@ -31,7 +31,7 @@ describe('useCoreAccessStore', () => {
});
it('adds a new tab if it does not exist', () => {
const store = useCoreTabbarStore();
const store = useTabbarStore();
const newTab: any = {
fullPath: '/new',
meta: {},
@@ -43,7 +43,7 @@ describe('useCoreAccessStore', () => {
});
it('updates an existing tab instead of adding a new one', () => {
const store = useCoreTabbarStore();
const store = useTabbarStore();
const initialTab: any = {
fullPath: '/existing',
meta: {},
@@ -59,7 +59,7 @@ describe('useCoreAccessStore', () => {
});
it('closes all tabs', async () => {
const store = useCoreTabbarStore();
const store = useTabbarStore();
store.tabs = [
{ fullPath: '/home', meta: {}, name: 'Home', path: '/home' },
] as any;
@@ -72,7 +72,7 @@ describe('useCoreAccessStore', () => {
});
it('closes a non-affix tab', () => {
const store = useCoreTabbarStore();
const store = useTabbarStore();
const tab: any = {
fullPath: '/closable',
meta: {},
@@ -85,7 +85,7 @@ describe('useCoreAccessStore', () => {
});
it('does not close an affix tab', () => {
const store = useCoreTabbarStore();
const store = useTabbarStore();
const affixTab: any = {
fullPath: '/affix',
meta: { affixTab: true },
@@ -98,14 +98,14 @@ describe('useCoreAccessStore', () => {
});
it('returns all cache tabs', () => {
const store = useCoreTabbarStore();
const store = useTabbarStore();
store.cachedTabs.add('Home');
store.cachedTabs.add('About');
expect(store.getCachedTabs).toEqual(['Home', 'About']);
});
it('returns all tabs, including affix tabs', () => {
const store = useCoreTabbarStore();
const store = useTabbarStore();
const normalTab: any = {
fullPath: '/normal',
meta: {},
@@ -125,7 +125,7 @@ describe('useCoreAccessStore', () => {
});
it('navigates to a specific tab', async () => {
const store = useCoreTabbarStore();
const store = useTabbarStore();
const tab: any = { meta: {}, name: 'Dashboard', path: '/dashboard' };
await store._goToTab(tab, router);
@@ -138,7 +138,7 @@ describe('useCoreAccessStore', () => {
});
it('closes multiple tabs by paths', async () => {
const store = useCoreTabbarStore();
const store = useTabbarStore();
store.addTab({
fullPath: '/home',
meta: {},
@@ -165,7 +165,7 @@ describe('useCoreAccessStore', () => {
});
it('closes all tabs to the left of the specified tab', async () => {
const store = useCoreTabbarStore();
const store = useTabbarStore();
store.addTab({
fullPath: '/home',
meta: {},
@@ -193,7 +193,7 @@ describe('useCoreAccessStore', () => {
});
it('closes all tabs except the specified tab', async () => {
const store = useCoreTabbarStore();
const store = useTabbarStore();
store.addTab({
fullPath: '/home',
meta: {},
@@ -221,7 +221,7 @@ describe('useCoreAccessStore', () => {
});
it('closes all tabs to the right of the specified tab', async () => {
const store = useCoreTabbarStore();
const store = useTabbarStore();
const targetTab: any = {
fullPath: '/home',
meta: {},
@@ -249,7 +249,7 @@ describe('useCoreAccessStore', () => {
});
it('closes the tab with the specified key', async () => {
const store = useCoreTabbarStore();
const store = useTabbarStore();
const keyToClose = '/about';
store.addTab({
fullPath: '/home',
@@ -279,7 +279,7 @@ describe('useCoreAccessStore', () => {
});
it('refreshes the current tab', async () => {
const store = useCoreTabbarStore();
const store = useTabbarStore();
const currentTab: any = {
fullPath: '/dashboard',
meta: { name: 'Dashboard' },

View File

@@ -7,7 +7,7 @@ import { openWindow, startProgress, stopProgress } from '@vben-core/shared';
import { acceptHMRUpdate, defineStore } from 'pinia';
interface TabsState {
interface TabbarState {
/**
* @zh_CN 当前打开的标签页列表缓存
*/
@@ -37,7 +37,7 @@ interface TabsState {
/**
* @zh_CN 访问权限相关
*/
export const useCoreTabbarStore = defineStore('core-tabbar', {
export const useTabbarStore = defineStore('core-tabbar', {
actions: {
/**
* Close tabs in bulk
@@ -441,7 +441,7 @@ export const useCoreTabbarStore = defineStore('core-tabbar', {
storage: sessionStorage,
},
],
state: (): TabsState => ({
state: (): TabbarState => ({
cachedTabs: new Set(),
dragEndIndex: 0,
excludeCachedTabs: new Set(),
@@ -454,7 +454,7 @@ export const useCoreTabbarStore = defineStore('core-tabbar', {
// 解决热更新问题
const hot = import.meta.hot;
if (hot) {
hot.accept(acceptHMRUpdate(useCoreTabbarStore, hot));
hot.accept(acceptHMRUpdate(useTabbarStore, hot));
}
/**

View File

@@ -0,0 +1,37 @@
import { createPinia, setActivePinia } from 'pinia';
import { beforeEach, describe, expect, it } from 'vitest';
import { useUserStore } from './user';
describe('useUserStore', () => {
beforeEach(() => {
setActivePinia(createPinia());
});
it('returns correct userInfo', () => {
const store = useUserStore();
const userInfo: any = { name: 'Jane Doe', roles: [{ value: 'user' }] };
store.setUserInfo(userInfo);
expect(store.userInfo).toEqual(userInfo);
});
// 测试重置用户信息时的行为
it('clears userInfo and userRoles when setting null userInfo', () => {
const store = useUserStore();
store.setUserInfo({
roles: [{ roleName: 'User', value: 'user' }],
} as any);
expect(store.userInfo).not.toBeNull();
expect(store.userRoles.length).toBeGreaterThan(0);
store.setUserInfo(null as any); // 重置用户信息
expect(store.userInfo).toBeNull();
expect(store.userRoles).toEqual([]);
});
// 测试在没有用户角色时返回空数组
it('returns an empty array for userRoles if not set', () => {
const store = useUserStore();
expect(store.userRoles).toEqual([]);
});
});

View File

@@ -0,0 +1,63 @@
import { acceptHMRUpdate, defineStore } from 'pinia';
interface BasicUserInfo {
/**
* 头像
*/
avatar: string;
/**
* 用户昵称
*/
realName: string;
/**
* 用户角色
*/
roles?: string[];
/**
* 用户id
*/
userId: string;
/**
* 用户名
*/
username: string;
}
interface AccessState {
/**
* 用户信息
*/
userInfo: BasicUserInfo | null;
/**
* 用户角色
*/
userRoles: string[];
}
/**
* @zh_CN 用户信息相关
*/
export const useUserStore = defineStore('core-user', {
actions: {
setUserInfo(userInfo: BasicUserInfo | null) {
// 设置用户信息
this.userInfo = userInfo;
// 设置角色信息
const roles = userInfo?.roles ?? [];
this.setUserRoles(roles);
},
setUserRoles(roles: string[]) {
this.userRoles = roles;
},
},
state: (): AccessState => ({
userInfo: null,
userRoles: [],
}),
});
// 解决热更新问题
const hot = import.meta.hot;
if (hot) {
hot.accept(acceptHMRUpdate(useUserStore, hot));
}

View File

@@ -1,5 +1,7 @@
import type { Pinia } from 'pinia';
import type { App } from 'vue';
import { createPinia } from 'pinia';
let pinia: Pinia;
@@ -14,7 +16,7 @@ export interface InitStoreOptions {
/**
* @zh_CN 初始化pinia
*/
export async function initStore(options: InitStoreOptions) {
export async function initStores(app: App, options: InitStoreOptions) {
const { createPersistedState } = await import('pinia-plugin-persistedstate');
pinia = createPinia();
const { namespace } = options;
@@ -25,6 +27,7 @@ export async function initStore(options: InitStoreOptions) {
storage: localStorage,
}),
);
app.use(pinia);
return pinia;
}