workout.js 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. import Workout from "../models/Workout.js";
  2. const createRoute = async (req, res, next)=>{
  3. try{
  4. const workout = createWorkout(req.body, res.locals.user._id);
  5. await workout.save();
  6. res.json(responseWorkout(workout));
  7. }catch(e){next(e)}
  8. }
  9. const getRoute = async (req, res, next)=>{
  10. try{
  11. const workouts = await Workout.find({user: res.locals.user._id});
  12. res.json(workouts.map(w => responseWorkout(w)));
  13. }catch(e){next(e)}
  14. }
  15. /*
  16. Create a new Workout object
  17. @param {Object} - Body data from the request
  18. @param {ObjectId} userId - ID of the user creating the workout
  19. @return {Workout} - Workout object
  20. */
  21. const createWorkout = (data, userId)=>{
  22. return new Workout({
  23. user: userId,
  24. name: data.name,
  25. exercises: data.exercises
  26. });
  27. }
  28. /*
  29. Create a new workout object for sending to the frontend
  30. @param {Workout} workout - Workout object
  31. @return {Object} - Modified Workout object
  32. */
  33. const responseWorkout = (workout)=>{
  34. return {
  35. id: workout._id,
  36. name: workout.name,
  37. exercises: workout.exercises
  38. };
  39. }
  40. export {
  41. createRoute,
  42. getRoute
  43. }