|
|
@@ -1,5 +1,7 @@
|
|
|
import Workout from "../models/Workout.js";
|
|
|
|
|
|
+import {HttpError} from "../HttpError.js";
|
|
|
+
|
|
|
const createRoute = async (req, res, next)=>{
|
|
|
try{
|
|
|
const workout = createWorkout(req.body, res.locals.user._id);
|
|
|
@@ -15,6 +17,17 @@ const getRoute = async (req, res, next)=>{
|
|
|
}catch(e){next(e)}
|
|
|
}
|
|
|
|
|
|
+const addNoteRoute = async (req, res, next)=>{
|
|
|
+ try{
|
|
|
+ const workout = await Workout.find({_id: req.params.workoutId});
|
|
|
+ confirmOwnership(workout, res.locals.user);
|
|
|
+ const exercise = findExercise(workout, req.body.exerciseId);
|
|
|
+ exercise.notes = req.body.note;
|
|
|
+ await workout.save();
|
|
|
+ res.json(responseWorkout(workout));
|
|
|
+ }catch(e){next(e)}
|
|
|
+}
|
|
|
+
|
|
|
/*
|
|
|
Create a new Workout object
|
|
|
@param {Object} - Body data from the request
|
|
|
@@ -29,6 +42,32 @@ const createWorkout = (data, userId)=>{
|
|
|
});
|
|
|
}
|
|
|
|
|
|
+/*
|
|
|
+ Throw error if user does not own workout
|
|
|
+ @param {Workout} workout - Workout object
|
|
|
+ @param {User} user - User object
|
|
|
+ */
|
|
|
+const confirmOwnership = (workout, user)=>{
|
|
|
+ if(workout.user.toString() !== user._id.toString()){
|
|
|
+ throw new HttpError(403, "Unauthorized");
|
|
|
+ }
|
|
|
+}
|
|
|
+
|
|
|
+/*
|
|
|
+ Retrieve a single exercise from a workout
|
|
|
+ @param {Workout} workout - Workout object
|
|
|
+ @param {String} exerciseId - ID of the exercise to retrieve
|
|
|
+ @return {Object} - Exercise object
|
|
|
+ */
|
|
|
+const findExercise = (workout, exerciseId)=>{
|
|
|
+ for(let i = 0; i < workout.exercises.length; i++){
|
|
|
+ if(workout.exercises._id.toString === exerciseId){
|
|
|
+ return workout.exercises[i];
|
|
|
+ }
|
|
|
+ }
|
|
|
+ return null;
|
|
|
+}
|
|
|
+
|
|
|
/*
|
|
|
Create a new workout object for sending to the frontend
|
|
|
@param {Workout} workout - Workout object
|
|
|
@@ -44,5 +83,6 @@ const responseWorkout = (workout)=>{
|
|
|
|
|
|
export {
|
|
|
createRoute,
|
|
|
- getRoute
|
|
|
+ getRoute,
|
|
|
+ addNoteRoute
|
|
|
}
|