This commit is contained in:
2025-06-03 11:44:51 +03:00
parent 074d6674b8
commit 8c42b7dadd
18 changed files with 6923 additions and 190 deletions

View File

@@ -1,54 +1,20 @@
import { create as batshitCreate, keyResolver } from "@yornaath/batshit";
import { create } from "zustand";
import { immer } from "zustand/middleware/immer";
import { getUser } from "~/lib/api/client/user";
import type { FullUser, PartialUser, UserId } from "~/lib/api/types";
type UsersStore = {
users: Record<UserId, PartialUser>;
currentUserId: UserId | undefined;
fetchUsersIfNotPresent: (userIds: UserId[]) => Promise<void>;
addUser: (user: PartialUser) => void;
removeUser: (userId: UserId) => void;
setCurrentUserId: (userId: UserId) => void;
getCurrentUser: () => FullUser | undefined;
};
const usersFetcher = batshitCreate({
fetcher: async (userIds: UserId[]) => {
const users = [];
for (const userId of userIds) {
users.push(getUser(userId));
}
return await Promise.all(users);
},
resolver: keyResolver("id"),
});
export const useUsersStore = create<UsersStore>()(
immer((set, get) => ({
users: {},
currentUserId: undefined,
fetchUsersIfNotPresent: async (userIds) => {
const userPromises: Promise<PartialUser>[] = [];
for (const userId of userIds) {
const user = get().users[userId];
if (!user) {
userPromises.push(usersFetcher.fetch(userId));
}
}
const users = await Promise.all(userPromises);
const activeUsers = users.filter(Boolean);
set((state) => {
for (const user of activeUsers) {
if (user?.id) state.users[user.id] = user;
}
});
},
addUser: (user) =>
set((state) => {
if (user.id !== get().currentUserId) state.users[user.id] = user;
@@ -68,6 +34,9 @@ export const useUsersStore = create<UsersStore>()(
state.currentUserId = userId;
}),
getCurrentUser: () => (get().currentUserId ? (get().users[get().currentUserId!] as FullUser) : undefined),
getCurrentUser: () => {
const currentUserId = get().currentUserId;
return currentUserId ? (get().users[currentUserId] as FullUser) : undefined;
},
})),
);