el.xwx.moe/store/collections.ts

91 lines
2.2 KiB
TypeScript
Raw Normal View History

2023-02-18 21:32:02 -06:00
import { create } from "zustand";
2023-06-16 07:55:21 -05:00
import { CollectionIncludingMembersAndLinkCount } from "@/types/global";
import useTagStore from "./tags";
2023-02-18 21:32:02 -06:00
2023-03-22 18:11:54 -05:00
type CollectionStore = {
2023-06-16 07:55:21 -05:00
collections: CollectionIncludingMembersAndLinkCount[];
2023-02-18 21:32:02 -06:00
setCollections: () => void;
2023-06-16 07:55:21 -05:00
addCollection: (
body: CollectionIncludingMembersAndLinkCount
) => Promise<boolean>;
2023-05-26 23:11:29 -05:00
updateCollection: (
2023-06-16 07:55:21 -05:00
collection: CollectionIncludingMembersAndLinkCount
2023-05-26 23:11:29 -05:00
) => Promise<boolean>;
removeCollection: (collectionId: number) => Promise<boolean>;
2023-02-18 21:32:02 -06:00
};
2023-03-22 18:11:54 -05:00
const useCollectionStore = create<CollectionStore>()((set) => ({
2023-02-18 21:32:02 -06:00
collections: [],
setCollections: async () => {
const response = await fetch("/api/routes/collections");
const data = await response.json();
if (response.ok) set({ collections: data.response });
},
2023-04-24 16:30:40 -05:00
addCollection: async (body) => {
2023-02-18 21:32:02 -06:00
const response = await fetch("/api/routes/collections", {
2023-04-24 16:30:40 -05:00
body: JSON.stringify(body),
2023-02-18 21:32:02 -06:00
headers: {
"Content-Type": "application/json",
},
method: "POST",
});
const data = await response.json();
if (response.ok)
set((state) => ({
collections: [...state.collections, data.response],
}));
2023-04-24 16:30:40 -05:00
return response.ok;
2023-02-18 21:32:02 -06:00
},
updateCollection: async (collection) => {
const response = await fetch("/api/routes/collections", {
body: JSON.stringify(collection),
headers: {
"Content-Type": "application/json",
},
method: "PUT",
});
const data = await response.json();
console.log(data);
if (response.ok)
set((state) => ({
collections: state.collections.map((e) =>
2023-05-01 15:00:23 -05:00
e.id === data.response.id ? data.response : e
),
}));
return response.ok;
},
removeCollection: async (id) => {
const response = await fetch("/api/routes/collections", {
body: JSON.stringify({ id }),
headers: {
"Content-Type": "application/json",
},
method: "DELETE",
});
const data = await response.json();
console.log(data);
if (response.ok) {
set((state) => ({
collections: state.collections.filter((e) => e.id !== id),
}));
useTagStore.getState().setTags();
}
return response.ok;
2023-02-18 21:32:02 -06:00
},
}));
2023-03-22 18:11:54 -05:00
export default useCollectionStore;