-
Notifications
You must be signed in to change notification settings - Fork 0
/
wishlist_handler.js
95 lines (82 loc) · 2.6 KB
/
wishlist_handler.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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
const express = require('express');
const { MongoClient } = require('mongodb');
const router = express.Router();
const uri = "mongodb://127.0.0.1:27017/";
const dbName = "test";
// Database connection helper
async function getDb() {
const client = await MongoClient.connect(uri);
return { client, db: client.db(dbName) };
}
// GET - Read wishlist items
router.get('/wishlist/:emailId', async (req, res) => {
try {
const { client, db } = await getDb();
const result = await db.collection("customers")
.find({ email: req.params.emailId })
.toArray();
await client.close();
res.json(result);
} catch (error) {
res.status(500).json({ error: error.message });
}
});
// POST - Create new wishlist
router.post('/wishlist', async (req, res) => {
try {
const { emailId, link, title, price } = req.body;
const { client, db } = await getDb();
const existingUser = await db.collection("customers")
.findOne({ email: emailId });
if (existingUser) {
await db.collection("customers").updateOne(
{ email: emailId },
{
$push: {
link: link,
title: title,
price: price
}
}
);
} else {
await db.collection("customers").insertOne({
email: emailId,
link: [link],
title: [title],
price: [price]
});
}
await client.close();
res.status(201).json({ message: "Wishlist item added successfully" });
} catch (error) {
res.status(500).json({ error: error.message });
}
});
// DELETE - Remove item from wishlist
router.delete('/wishlist/:emailId', async (req, res) => {
try {
const { link, title, price } = req.body;
const { client, db } = await getDb();
await db.collection("customers").updateOne(
{ email: req.params.emailId },
{
$pull: {
link: link,
title: title,
price: price
}
}
);
await client.close();
res.json({ message: "Item removed from wishlist" });
} catch (error) {
res.status(500).json({ error: error.message });
}
});
// Error handling middleware
router.use((err, req, res, next) => {
console.error(err.stack);
res.status(500).json({ error: 'Something went wrong!' });
});
module.exports = router;