refactor: 优化数据加载逻辑.

This commit is contained in:
lijiahangmax
2023-12-02 23:36:02 +08:00
parent 9f35fb855d
commit a22f30a8b4
19 changed files with 155 additions and 117 deletions

View File

@@ -1,5 +1,8 @@
import type { CacheState } from './types';
import type { AxiosResponse } from 'axios';
import { defineStore } from 'pinia';
import { getUserList } from '@/api/user/user';
import { getRoleList } from '@/api/user/role';
export type CacheType = 'users' | 'menus' | 'roles'
| 'host' | 'hostGroups' | 'hostTags' | 'hostKeys' | 'hostIdentities'
@@ -7,7 +10,6 @@ export type CacheType = 'users' | 'menus' | 'roles'
export default defineStore('cache', {
state: (): CacheState => ({
users: [],
menus: [],
roles: [],
hosts: [],
@@ -29,13 +31,40 @@ export default defineStore('cache', {
// 清空
reset(...names: CacheType[]) {
for (let name of names) {
this[name] = [];
this[name] = undefined;
}
},
// 清除全部
clear() {
this.$reset();
}
},
},
// 加载数据
async load<T>(name: CacheType, loader: () => Promise<AxiosResponse<T>>, onErrorValue = []) {
// 尝试直接从缓存中获取数据
if (this[name]) {
return this[name] as T;
}
// 加载数据
try {
const { data } = await loader();
this[name] = data;
return this[name] as T;
} catch (e) {
return onErrorValue as T;
}
},
// 获取用户列表
async loadUsers() {
return await this.load('users', getUserList);
},
// 获取角色列表
async loadRoles() {
return await this.load('roles', getRoleList);
},
}
});

View File

@@ -9,15 +9,15 @@ import type { HostIdentityQueryResponse } from '@/api/asset/host-identity';
import type { DictKeyQueryResponse } from '@/api/system/dict-key';
export interface CacheState {
users: UserQueryResponse[];
menus: MenuQueryResponse[];
roles: RoleQueryResponse[];
hostTags: TagQueryResponse[];
hosts: HostQueryResponse[];
hostGroups: HostGroupQueryResponse[];
hostKeys: HostKeyQueryResponse[];
hostIdentities: HostIdentityQueryResponse[];
dictKeys: DictKeyQueryResponse[];
users?: UserQueryResponse[];
menus?: MenuQueryResponse[];
roles?: RoleQueryResponse[];
hostTags?: TagQueryResponse[];
hosts?: HostQueryResponse[];
hostGroups?: HostGroupQueryResponse[];
hostKeys?: HostKeyQueryResponse[];
hostIdentities?: HostIdentityQueryResponse[];
dictKeys?: DictKeyQueryResponse[];
[key: string]: unknown;
}