Refactor server list as hash table

This commit is contained in:
jeffvli 2023-04-25 01:36:26 -07:00
parent 2ce49fc54e
commit 1cbd61888f

View file

@ -11,14 +11,14 @@ import { ServerListItem } from '/@/renderer/types';
export interface AuthState { export interface AuthState {
currentServer: ServerListItem | null; currentServer: ServerListItem | null;
deviceId: string; deviceId: string;
serverList: ServerListItem[]; serverList: Record<string, ServerListItem>;
} }
export interface AuthSlice extends AuthState { export interface AuthSlice extends AuthState {
actions: { actions: {
addServer: (args: ServerListItem) => void; addServer: (args: ServerListItem) => void;
deleteServer: (id: string) => void; deleteServer: (id: string) => void;
getServer: (id?: string) => ServerListItem | undefined; getServer: (id: string) => ServerListItem | undefined;
setCurrentServer: (server: ServerListItem | null) => void; setCurrentServer: (server: ServerListItem | null) => void;
updateServer: (id: string, args: Partial<ServerListItem>) => void; updateServer: (id: string, args: Partial<ServerListItem>) => void;
}; };
@ -31,19 +31,20 @@ export const useAuthStore = create<AuthSlice>()(
actions: { actions: {
addServer: (args) => { addServer: (args) => {
set((state) => { set((state) => {
state.serverList.push(args); state.serverList[args.id] = args;
}); });
}, },
deleteServer: (id) => { deleteServer: (id) => {
set((state) => { set((state) => {
state.serverList = state.serverList.filter((credential) => credential.id !== id); delete state.serverList[id];
if (state.currentServer?.id === id) { if (state.currentServer?.id === id) {
state.currentServer = null; state.currentServer = null;
} }
}); });
}, },
getServer: (id) => { getServer: (id) => {
return get().serverList.find((server) => server.id === id); return get().serverList[id];
}, },
setCurrentServer: (server) => { setCurrentServer: (server) => {
set((state) => { set((state) => {
@ -61,16 +62,17 @@ export const useAuthStore = create<AuthSlice>()(
}, },
updateServer: (id: string, args: Partial<ServerListItem>) => { updateServer: (id: string, args: Partial<ServerListItem>) => {
set((state) => { set((state) => {
const server = state.serverList.find((server) => server.id === id); state.serverList[id] = { ...state.serverList[id], ...args };
if (server) {
Object.assign(server, { ...server, ...args }); if (state.currentServer?.id === id) {
state.currentServer = { ...state.serverList[id], ...args };
} }
}); });
}, },
}, },
currentServer: null, currentServer: null,
deviceId: nanoid(), deviceId: nanoid(),
serverList: [], serverList: {},
})), })),
{ name: 'store_authentication' }, { name: 'store_authentication' },
), ),