Advertisement
krle997

Untitled

Dec 12th, 2024
56
0
19 days
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. export const copyWorkouts2 = async (
  2.   userId,
  3.   partialWorkoutMap,
  4.   shouldAuthorize = true
  5. ) => {
  6.   const workoutIds = Object.keys(partialWorkoutMap);
  7.   const workouts = await getWorkoutsByIds(workoutIds);
  8.  
  9.   const role = await getUsersRole(userId);
  10.   const isClient = role.roleId === 1;
  11.   const isTrainer = role.roleId === 2;
  12.  
  13.   if (shouldAuthorize && isTrainer && !await authorizeWorkouts(userId, workouts)) {
  14.     return [Status.UNAUTHORIZED, "Unauthorized", null];
  15.   }
  16.  
  17.   if (shouldAuthorize && isClient) {
  18.     return [Status.UNAUTHORIZED, "Unauthorized", null];
  19.   }
  20.  
  21.   const newWorkouts = workouts.map((workout) => {
  22.     const partialWorkout = partialWorkoutMap[workout.id];
  23.     const createdAt = new Date().toISOString();
  24.  
  25.     const returnObject = {
  26.       ...workout,
  27.       ...partialWorkout,
  28.       createdAt,
  29.       updatedAt: createdAt,
  30.     };
  31.  
  32.     if (isTrainer && returnObject.default) {
  33.       returnObject.trainerId = userId;
  34.     }
  35.  
  36.     delete returnObject.id;
  37.     return returnObject;
  38.   });
  39.  
  40.   if (newWorkouts.length === 0) {
  41.     return [Status.OK, null, []];
  42.   }
  43.  
  44.   const [id] = await insertWorkout(newWorkouts);
  45.  
  46.   for (const [index, workout] of workouts.entries()) {
  47.     const newWorkoutId = id + index;
  48.  
  49.     try {
  50.       const exerciseIds = await pluckExerciseIds(workout.id, "workoutId");
  51.       const partialExerciseMap = {};
  52.  
  53.       // const newWorkout = newWorkouts.find((newWorkout) => newWorkout.id === workout.id);
  54.  
  55.       exerciseIds.forEach((id) => {
  56.         partialExerciseMap[id] = {
  57.           workoutId: newWorkoutId,
  58.  
  59.         };
  60.       });
  61.  
  62.       const [error, exercises] = await copyExercises2(
  63.         userId,
  64.         partialExerciseMap,
  65.         false
  66.       );
  67.  
  68.       if (data) {
  69.         newWorkouts[index].exercises = exercises;
  70.       }
  71.     } catch (error) {
  72.       console.error(error);
  73.     }
  74.  
  75.     newWorkouts[index].id = newWorkoutId;
  76.   }
  77.  
  78.   return [Status.OK, null, newWorkouts];
  79. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement