-
Notifications
You must be signed in to change notification settings - Fork 112
Expand file tree
/
Copy pathUserController.js
More file actions
61 lines (58 loc) · 1.99 KB
/
UserController.js
File metadata and controls
61 lines (58 loc) · 1.99 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
const User = require("../models/UserModel");
module.exports.getLikedMovies = async (req, res) => {
try {
const { email } = req.params;
const user = await await User.findOne({ email });
if (user) {
return res.json({ msg: "success", movies: user.likedMovies });
} else return res.json({ msg: "User with given email not found." });
} catch (error) {
return res.json({ msg: "Error fetching movies." });
}
};
module.exports.addToLikedMovies = async (req, res) => {
try {
const { email, data } = req.body;
const user = await await User.findOne({ email });
if (user) {
const { likedMovies } = user;
const movieAlreadyLiked = likedMovies.find(({ id }) => id === data.id);
if (!movieAlreadyLiked) {
await User.findByIdAndUpdate(
user._id,
{
likedMovies: [...user.likedMovies, data],
},
{ new: true }
);
} else return res.json({ msg: "Movie already added to the liked list." });
} else await User.create({ email, likedMovies: [data] });
return res.json({ msg: "Movie successfully added to liked list." });
} catch (error) {
return res.json({ msg: "Error adding movie to the liked list" });
}
};
module.exports.removeFromLikedMovies = async (req, res) => {
try {
const { email, movieId } = req.body;
const user = await User.findOne({ email });
if (user) {
const movies = user.likedMovies;
const movieIndex = movies.findIndex(({ id }) => id === movieId);
if (movieIndex < 0) {
res.status(400).send({ msg: "Movie not found." });
}
movies.splice(movieIndex, 1);
await User.findByIdAndUpdate(
user._id,
{
likedMovies: movies,
},
{ new: true }
);
return res.json({ msg: "Movie successfully removed.", movies });
} else return res.json({ msg: "User with given email not found." });
} catch (error) {
return res.json({ msg: "Error removing movie to the liked list" });
}
};