-
Notifications
You must be signed in to change notification settings - Fork 0
/
favourites.js
71 lines (61 loc) · 1.91 KB
/
favourites.js
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
const express = require("express");
const router = express.Router();
const db = require("./database");
// Route to add pokemon to favourites
router.post("/add", (req, res) => {
const { userId, pokemon } = req.body;
const query = "SELECT * FROM favourites WHERE userId = ? AND pokemon = ?";
db.all(query, [userId, pokemon], (err, rows) => {
if (err) {
throw err;
}
if (rows.length === 0) {
db.all(
`INSERT INTO favourites (userId, pokemon) VALUES (?,?)`,
[userId, pokemon],
(err) => {
if (err) {
throw err;
}
return res.send(`Pokemon ${pokemon} is added to favourites!`);
}
);
} else {
res.status(409).send("Pokemon is already in favourites");
}
});
});
// Route to remove pokemon from favourites
router.post("/remove", (req, res) => {
const { userId, pokemon } = req.body;
const query = "DELETE FROM favourites WHERE userId = ? AND pokemon = ?";
db.all(query, [userId, pokemon], function (err) {
if (err) {
return res.status(500).json({ error: err.message });
}
if (this.changes === 0) {
return res.status(404).json({ message: "Favorite item not found" });
}
res.json({ message: "Favorite item removed successfully!" });
});
});
router.post("/removeall", (req, res) => {
const { userId } = req.body;
const query = "DELETE FROM favourites WHERE userId = ?";
db.all(query, [userId], function (err) {
if (!!err) {
return res.status(500).send({ error: err.message });
}
res.send("Your favourites are flushed!");
});
});
// Route to get favourite pokemons from db
router.get("/get/:userId", (req, res) => {
const userId = req.params.userId;
const query = "SELECT * FROM favourites WHERE userId = ?";
db.all(query, [userId], (err, rows) => {
if (err) return res.status(500).send("Server error");
res.json(rows);
});
});
module.exports = router;