-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathworkout.js
More file actions
90 lines (73 loc) · 2.08 KB
/
workout.js
File metadata and controls
90 lines (73 loc) · 2.08 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
const DB = require('./db.json');
const { saveToDatabase } = require('./utils');
const getAllWorkouts = () => {
try {
return DB.workouts;
} catch (error) {
throw { status: 500, message: error };
}
};
const getOneWorkout = (workoutId) => {
try {
const workout = DB.workouts.find(workout => workout.id === workoutId);
if (!workout)
throw {
status: 400,
message: `Can't find workout with the id '${workoutId}'`,
};
return workout;
} catch (error) {
throw { status: error?.status || 500, message: error?.message || error };
}
};
const createNewWorkout = (newWorkout) => {
try {
const isAlreadyAdded =
DB.workouts.findIndex((workout) => workout.name === newWorkout.name) > -1;
if (isAlreadyAdded)
throw {
status: 400,
message: `Workout with the name ${newWorkout.name} already exists`
}
DB.workouts.push(newWorkout);
saveToDatabase(DB);
return newWorkout;
} catch (error) {
throw { status: error?.status || 500, message: error?.message || error };
}
};
const updateOneWorkout = (workoutId, changes) => {
try {
const indexForUpdate = DB.workouts.findIndex(workout => workout.id === workoutId);
if (indexForUpdate === -1)
return;
const updatedWorkout = {
...DB.workouts[indexForUpdate],
...changes,
updatedAt: new Date().toLocaleString("en-US", { timezone: "UTC" })
}
DB.workouts[indexForUpdate] = updatedWorkout;
saveToDatabase(DB);
return updatedWorkout;
} catch (error) {
throw { status: error?.status || 500, message: error?.message || error };
}
};
const deleteOneWorkout = (workoutId) => {
try {
const indexforDeletion = DB.workouts.findIndex(workout => workout.id === workoutId);
if (indexforDeletion === -1)
return;
DB.workouts.splice(indexforDeletion, 1);
saveToDatabase(DB);
} catch (error) {
throw { status: error?.status || 500, message: error?.message || error };
}
};
module.exports = {
getAllWorkouts,
createNewWorkout,
getOneWorkout,
updateOneWorkout,
deleteOneWorkout
};