2023-03-05 15:03:20 -06:00
|
|
|
import { create } from "zustand";
|
2023-03-10 13:25:33 -06:00
|
|
|
import { ExtendedLink, NewLink } from "@/types/global";
|
2023-03-05 15:03:20 -06:00
|
|
|
|
2023-03-22 18:11:54 -05:00
|
|
|
type LinkStore = {
|
2023-03-10 13:25:33 -06:00
|
|
|
links: ExtendedLink[];
|
2023-03-05 15:03:20 -06:00
|
|
|
setLinks: () => void;
|
2023-03-08 15:31:24 -06:00
|
|
|
addLink: (linkName: NewLink) => Promise<boolean>;
|
2023-03-10 13:25:33 -06:00
|
|
|
updateLink: (link: ExtendedLink) => void;
|
2023-03-23 10:25:17 -05:00
|
|
|
removeLink: (link: ExtendedLink) => void;
|
2023-03-05 15:03:20 -06:00
|
|
|
};
|
|
|
|
|
2023-03-22 18:11:54 -05:00
|
|
|
const useLinkStore = create<LinkStore>()((set) => ({
|
2023-03-05 15:03:20 -06:00
|
|
|
links: [],
|
|
|
|
setLinks: async () => {
|
|
|
|
const response = await fetch("/api/routes/links");
|
|
|
|
|
|
|
|
const data = await response.json();
|
|
|
|
|
|
|
|
if (response.ok) set({ links: data.response });
|
|
|
|
},
|
|
|
|
addLink: async (newLink) => {
|
|
|
|
const response = await fetch("/api/routes/links", {
|
|
|
|
body: JSON.stringify(newLink),
|
|
|
|
headers: {
|
|
|
|
"Content-Type": "application/json",
|
|
|
|
},
|
|
|
|
method: "POST",
|
|
|
|
});
|
|
|
|
|
|
|
|
const data = await response.json();
|
|
|
|
|
|
|
|
if (response.ok)
|
|
|
|
set((state) => ({
|
|
|
|
links: [...state.links, data.response],
|
|
|
|
}));
|
2023-03-08 15:31:24 -06:00
|
|
|
|
|
|
|
return response.ok;
|
2023-03-05 15:03:20 -06:00
|
|
|
},
|
|
|
|
updateLink: (link) =>
|
|
|
|
set((state) => ({
|
|
|
|
links: state.links.map((c) => (c.id === link.id ? link : c)),
|
|
|
|
})),
|
2023-03-23 10:25:17 -05:00
|
|
|
removeLink: async (link) => {
|
|
|
|
const response = await fetch("/api/routes/links", {
|
|
|
|
body: JSON.stringify(link),
|
|
|
|
headers: {
|
|
|
|
"Content-Type": "application/json",
|
|
|
|
},
|
|
|
|
method: "DELETE",
|
|
|
|
});
|
|
|
|
|
|
|
|
const data = await response.json();
|
|
|
|
|
|
|
|
if (response.ok)
|
|
|
|
set((state) => ({
|
|
|
|
links: state.links.filter((e) => e.id !== link.id),
|
|
|
|
}));
|
|
|
|
|
|
|
|
console.log(data);
|
|
|
|
|
|
|
|
return response.ok;
|
2023-03-05 15:03:20 -06:00
|
|
|
},
|
|
|
|
}));
|
|
|
|
|
2023-03-22 18:11:54 -05:00
|
|
|
export default useLinkStore;
|