2024-05-02 08:17:56 -05:00
|
|
|
import { User as U } from "@prisma/client";
|
|
|
|
import { create } from "zustand";
|
|
|
|
|
|
|
|
interface User extends U {
|
|
|
|
subscriptions: {
|
|
|
|
active: boolean;
|
|
|
|
};
|
|
|
|
}
|
|
|
|
|
|
|
|
type ResponseObject = {
|
|
|
|
ok: boolean;
|
|
|
|
data: object | string;
|
|
|
|
};
|
|
|
|
|
|
|
|
type UserStore = {
|
|
|
|
users: User[];
|
2024-05-03 09:22:45 -05:00
|
|
|
setUsers: () => void;
|
|
|
|
addUser: (body: Partial<U>) => Promise<ResponseObject>;
|
2024-05-02 08:17:56 -05:00
|
|
|
removeUser: (userId: number) => Promise<ResponseObject>;
|
|
|
|
};
|
|
|
|
|
|
|
|
const useUserStore = create<UserStore>((set) => ({
|
|
|
|
users: [],
|
|
|
|
setUsers: async () => {
|
|
|
|
const response = await fetch("/api/v1/users");
|
|
|
|
|
|
|
|
const data = await response.json();
|
|
|
|
|
|
|
|
if (response.ok) set({ users: data.response });
|
2024-05-03 09:22:45 -05:00
|
|
|
else if (response.status === 401) window.location.href = "/dashboard";
|
2024-05-02 08:17:56 -05:00
|
|
|
},
|
2024-05-03 09:22:45 -05:00
|
|
|
addUser: async (body) => {
|
2024-05-02 08:17:56 -05:00
|
|
|
const response = await fetch("/api/v1/users", {
|
|
|
|
method: "POST",
|
2024-05-03 09:22:45 -05:00
|
|
|
body: JSON.stringify(body),
|
|
|
|
headers: {
|
|
|
|
"Content-Type": "application/json",
|
|
|
|
},
|
2024-05-02 08:17:56 -05:00
|
|
|
});
|
|
|
|
|
|
|
|
const data = await response.json();
|
|
|
|
|
|
|
|
if (response.ok)
|
|
|
|
set((state) => ({
|
|
|
|
users: [...state.users, data.response],
|
|
|
|
}));
|
|
|
|
|
|
|
|
return { ok: response.ok, data: data.response };
|
|
|
|
},
|
|
|
|
removeUser: async (userId) => {
|
|
|
|
const response = await fetch(`/api/v1/users/${userId}`, {
|
|
|
|
method: "DELETE",
|
|
|
|
});
|
|
|
|
|
|
|
|
const data = await response.json();
|
|
|
|
|
|
|
|
if (response.ok)
|
|
|
|
set((state) => ({
|
|
|
|
users: state.users.filter((user) => user.id !== userId),
|
|
|
|
}));
|
|
|
|
|
|
|
|
return { ok: response.ok, data: data.response };
|
|
|
|
},
|
|
|
|
}));
|
|
|
|
|
|
|
|
export default useUserStore;
|