Skip to content

Commit

Permalink
Saving Studies (#68)
Browse files Browse the repository at this point in the history
Co-authored-by: Ross Newman <[email protected]>
  • Loading branch information
DavidOB1 and ross3102 authored Dec 9, 2023
1 parent 3778dfc commit c146bf1
Show file tree
Hide file tree
Showing 5 changed files with 69 additions and 14 deletions.
21 changes: 14 additions & 7 deletions packages/api/src/routes/studies.ts
Original file line number Diff line number Diff line change
Expand Up @@ -52,13 +52,20 @@ router.post("/", (req, res, next) => {
.catch(next);
});

router.put("/:id", (req, res, next) => {
Study.updateOne({ _id: req.params["id"] }, req.body)
.then((study) => {
if (!study) throw new HttpError(404);
res.json(study);
})
.catch(next);
router.put("/:id", isAuthenticated, async (req, res, next) => {
try {
const study = await Study.findOneAndUpdate(
{ _id: req.params["id"] },
req.body,
{ upsert: true, new: true }
);
const user = req.user as HydratedDocument<IUser>;
if (!user.studies.includes(study._id))
await user.updateOne({ $push: { studies: study._id } });
res.json(study);
} catch (e) {
next();
}
});

export default router;
9 changes: 8 additions & 1 deletion packages/ui/src/api/studies.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,12 @@ const axiosInstance = axios.create({
axiosInstance.interceptors.response.use(
(response) => response,
(error) => {
// TODO fix this to instantly cause redirect to login
if (error.response.status === 401) {
const authStore = useAuthStore();
authStore.currentUser = null;
} else {
throw error;
}
}
);
Expand All @@ -25,6 +28,10 @@ async function deleteStudy(id: string) {
await axiosInstance.delete(`/studies/${id}`);
}

async function saveStudy(id: string, studyData: GetStudyResponse) {
await axiosInstance.put(`/studies/${id}`, studyData);
}

export interface ITaskInstance {
_id: string;
task: string;
Expand Down Expand Up @@ -55,4 +62,4 @@ async function getStudy(id: string) {
return result.data;
}

export default { getStudies, deleteStudy, getStudy };
export default { getStudies, deleteStudy, getStudy, saveStudy };
3 changes: 3 additions & 0 deletions packages/ui/src/pages/StudyBuilderPage/StudyBuilderPage.vue
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import TaskBank from "./components/TaskBank.vue";
import AppEditModal from "@/components/ui/AppEditModal.vue";
import { useTaskEditingStore } from "@/stores/taskEditing";
import TaskEditingPanel from "./components/TaskEditingPanel.vue";
import { useStudyBuilderStore } from "@/stores/studyBuilder";
const router = useRouter();
const authStore = useAuthStore();
Expand All @@ -16,12 +17,14 @@ if (!authStore.currentUser) {
router.push("/login");
}
const studyBuilderStore = useStudyBuilderStore();
const taskEditingStore = useTaskEditingStore();
</script>

<template>
<!-- This is sort of a hack to delete elements if they are dropped outside of sessions -->
<Draggable
v-loading="studyBuilderStore.isStudySaving"
class="flex-1 flex overflow-auto"
ghost-class="hidden"
:group="{ put: ['taskbar', 'session'] }"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,10 +14,6 @@ const draggableProps = {
handle: ".handle",
animation: 200,
};
const saveChanges = () => {
console.log("changes saved");
};
</script>

<template>
Expand Down Expand Up @@ -49,7 +45,7 @@ const saveChanges = () => {
</div>
<AppButton
class="text-base bg-gray-200 border border-black rounded-lg px-5 py-1 h-auto justify-center"
@click="saveChanges"
@click="studyBuilderStore.saveStudyStore"
>
Save Changes
</AppButton>
Expand Down
44 changes: 43 additions & 1 deletion packages/ui/src/stores/studyBuilder.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import mongoose from "mongoose";
import studiesAPI from "@/api/studies";
import tasksAPI from "@/api/tasks";
import type {
GetStudyResponse,
ICustomizedBattery,
ISession,
ITaskInstance,
Expand All @@ -20,6 +21,33 @@ export const useStudyBuilderStore = defineStore("studyBuilder", () => {
const route = useRoute();
const router = useRouter();
const queryClient = useQueryClient();
const { mutate } = useMutation({
mutationFn({
studyId,
...studyData
}: { studyId: string } & GetStudyResponse) {
return studiesAPI.saveStudy(studyId, studyData);
},
onMutate() {
isStudySaving.value = true;
},
async onSuccess() {
ElNotification({
title: "Saved!",
type: "success",
});
},
onError(err: AxiosError<Error>) {
ElNotification({
title: "Error saving study",
message: err.response?.data.message ?? "",
type: "error",
});
},
onSettled() {
isStudySaving.value = false;
},
});

function routeStudyId() {
if (route.name === "study") {
Expand All @@ -28,12 +56,13 @@ export const useStudyBuilderStore = defineStore("studyBuilder", () => {
return typeof idParam === "string" ? idParam : idParam[0];
}
}
return undefined;
return new mongoose.Types.ObjectId().toString();
}

const isNewStudy = ref(true);
const studyId = ref<string>();
const isStudyLoading = ref(false);
const isStudySaving = ref(false);
const name = ref<string>();
const description = ref<string>();
const taskData = ref<Record<string, ICustomizedBattery>>({});
Expand Down Expand Up @@ -173,17 +202,30 @@ export const useStudyBuilderStore = defineStore("studyBuilder", () => {
}
}

function saveStudyStore() {
if (isStudyLoading.value || isStudySaving.value) return;
mutate({
studyId: studyId.value!,
name: name.value ?? "",
description: description.value ?? "",
batteries: taskBank.value.map((id) => taskData.value[id]), // TODO: fix this
sessions: sessions.value.map((id) => sessionData.value[id]),
});
}

watch(() => route.params.id, initialize, { immediate: true });

return {
isStudyLoading,
isStudySaving,
name,
description,
taskBank,
taskData,
sessions,
sessionData,
addSession,
saveStudyStore,
handleChange,
addTaskInstance,
};
Expand Down

0 comments on commit c146bf1

Please sign in to comment.