workout.js 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. import Workout from "../models/Workout.js";
  2. import {HttpError} from "../HttpError.js";
  3. const createRoute = async (req, res, next)=>{
  4. try{
  5. const workout = createWorkout(req.body, res.locals.user._id);
  6. await workout.save();
  7. res.json(responseWorkout(workout));
  8. }catch(e){next(e)}
  9. }
  10. const getRoute = async (req, res, next)=>{
  11. try{
  12. const workouts = await Workout.find({user: res.locals.user._id});
  13. res.json(workouts.map(w => responseWorkout(w)));
  14. }catch(e){next(e)}
  15. }
  16. const addNoteRoute = async (req, res, next)=>{
  17. try{
  18. const workout = await Workout.findOne({_id: req.params.workoutId});
  19. confirmOwnership(workout, res.locals.user);
  20. const exercise = findExercise(workout, req.body.exercise);
  21. exercise.notes = req.body.note;
  22. await workout.save();
  23. res.json(responseWorkout(workout));
  24. }catch(e){next(e)}
  25. }
  26. /*
  27. Create a new Workout object
  28. @param {Object} - Body data from the request
  29. @param {ObjectId} userId - ID of the user creating the workout
  30. @return {Workout} - Workout object
  31. */
  32. const createWorkout = (data, userId)=>{
  33. return new Workout({
  34. user: userId,
  35. name: data.name,
  36. exercises: data.exercises
  37. });
  38. }
  39. /*
  40. Throw error if user does not own workout
  41. @param {Workout} workout - Workout object
  42. @param {User} user - User object
  43. */
  44. const confirmOwnership = (workout, user)=>{
  45. if(workout.user.toString() !== user._id.toString()){
  46. throw new HttpError(403, "Unauthorized");
  47. }
  48. }
  49. /*
  50. Retrieve a single exercise from a workout
  51. @param {Workout} workout - Workout object
  52. @param {String} exerciseId - ID of the exercise to retrieve
  53. @return {Object} - Exercise object
  54. */
  55. const findExercise = (workout, exerciseId)=>{
  56. for(let i = 0; i < workout.exercises.length; i++){
  57. if(workout.exercises[i]._id.toString() === exerciseId){
  58. return workout.exercises[i];
  59. }
  60. }
  61. return null;
  62. }
  63. /*
  64. Create a new workout object for sending to the frontend
  65. @param {Workout} workout - Workout object
  66. @return {Object} - Modified Workout object
  67. */
  68. const responseWorkout = (workout)=>{
  69. return {
  70. id: workout._id,
  71. name: workout.name,
  72. exercises: workout.exercises
  73. };
  74. }
  75. export {
  76. createRoute,
  77. getRoute,
  78. addNoteRoute
  79. }