Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- export const copyWorkouts2 = async (
- userId,
- partialWorkoutMap,
- shouldAuthorize = true
- ) => {
- const workoutIds = Object.keys(partialWorkoutMap);
- const workouts = await getWorkoutsByIds(workoutIds);
- const role = await getUsersRole(userId);
- const isClient = role.roleId === 1;
- const isTrainer = role.roleId === 2;
- if (shouldAuthorize && isTrainer && !await authorizeWorkouts(userId, workouts)) {
- return [Status.UNAUTHORIZED, "Unauthorized", null];
- }
- if (shouldAuthorize && isClient) {
- return [Status.UNAUTHORIZED, "Unauthorized", null];
- }
- const newWorkouts = workouts.map((workout) => {
- const partialWorkout = partialWorkoutMap[workout.id];
- const createdAt = new Date().toISOString();
- const returnObject = {
- ...workout,
- ...partialWorkout,
- createdAt,
- updatedAt: createdAt,
- };
- if (isTrainer && returnObject.default) {
- returnObject.trainerId = userId;
- }
- delete returnObject.id;
- return returnObject;
- });
- if (newWorkouts.length === 0) {
- return [Status.OK, null, []];
- }
- const [id] = await insertWorkout(newWorkouts);
- for (const [index, workout] of workouts.entries()) {
- const newWorkoutId = id + index;
- try {
- const exerciseIds = await pluckExerciseIds(workout.id, "workoutId");
- const partialExerciseMap = {};
- // const newWorkout = newWorkouts.find((newWorkout) => newWorkout.id === workout.id);
- exerciseIds.forEach((id) => {
- partialExerciseMap[id] = {
- workoutId: newWorkoutId,
- };
- });
- const [error, exercises] = await copyExercises2(
- userId,
- partialExerciseMap,
- false
- );
- if (data) {
- newWorkouts[index].exercises = exercises;
- }
- } catch (error) {
- console.error(error);
- }
- newWorkouts[index].id = newWorkoutId;
- }
- return [Status.OK, null, newWorkouts];
- };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement