74 lines
2.0 KiB
TypeScript
74 lines
2.0 KiB
TypeScript
import { Mission, Prisma } from "@repo/db";
|
|
import { MissionOptionalDefaults } from "@repo/db/zod";
|
|
import { serverApi } from "helpers/axios";
|
|
import { create } from "zustand";
|
|
import { toast } from "react-hot-toast";
|
|
import axios from "axios";
|
|
|
|
interface MissionStore {
|
|
missions: Mission[];
|
|
setMissions: (missions: Mission[]) => void;
|
|
getMissions: () => Promise<undefined>;
|
|
createMission: (mission: MissionOptionalDefaults) => Promise<Mission>;
|
|
deleteMission: (id: number) => Promise<void>;
|
|
editMission: (id: number, mission: Partial<Mission>) => Promise<void>;
|
|
}
|
|
|
|
export const useMissionsStore = create<MissionStore>((set) => ({
|
|
missions: [],
|
|
setMissions: (missions) => set({ missions }),
|
|
createMission: async (mission) => {
|
|
const { data } = await serverApi.put<Mission>("/mission", mission);
|
|
|
|
set((state) => ({ missions: [...state.missions, data] }));
|
|
return data;
|
|
},
|
|
editMission: async (id, mission) => {
|
|
const { data, status } = await serverApi.patch<Mission>(
|
|
`/mission/${id}`,
|
|
mission,
|
|
);
|
|
if (status.toString().startsWith("2") && data) {
|
|
set((state) => ({
|
|
missions: state.missions.map((m) => (m.id === id ? data : m)),
|
|
}));
|
|
toast.success("Mission updated successfully");
|
|
} else {
|
|
toast.error("Failed to update mission");
|
|
}
|
|
},
|
|
deleteMission: async (id) => {
|
|
serverApi
|
|
.delete(`/mission/${id}`)
|
|
.then((res) => {
|
|
if (res.status.toString().startsWith("2")) {
|
|
set((state) => ({
|
|
missions: state.missions.filter((mission) => mission.id !== id),
|
|
}));
|
|
toast.success("Mission deleted successfully");
|
|
} else {
|
|
toast.error("Failed to delete mission");
|
|
}
|
|
})
|
|
.catch((err) => {
|
|
toast.error("Failed to delete mission");
|
|
});
|
|
},
|
|
getMissions: async () => {
|
|
const { data } = await serverApi.post<Mission[]>("/mission", {
|
|
filter: {
|
|
OR: [{ state: "draft" }, { state: "running" }],
|
|
} as Prisma.MissionWhereInput,
|
|
});
|
|
set({ missions: data });
|
|
return undefined;
|
|
},
|
|
}));
|
|
|
|
useMissionsStore
|
|
.getState()
|
|
.getMissions()
|
|
.then(() => {
|
|
console.log("Missions loaded");
|
|
});
|