-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
105 lines (80 loc) · 2.19 KB
/
Copy pathindex.js
File metadata and controls
105 lines (80 loc) · 2.19 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
91
92
93
94
95
96
97
98
99
100
101
102
103
import { connectdb, getdb } from "./db.js";
import express from "express"
const app = express();
const port = 3000;
app.use(express.json());
const users = [];
// connect to database
connectdb();
// start server
app.listen(port, () => {
console.log(`server is running on port ${port}`);
});
// get products
app.get("/products", (req, res) => {
const db = getdb();
db
? res.status(404).send("No products found!")
: res.status(200).send(users);
});
// add product
app.post("/products", async (req, res) => {
try {
const db = getdb();
const product = req.body;
// check if product already exists
const existingProduct = await db
.collection("products")
.findOne({ id: product.id });
if (existingProduct) {
return res.status(409).send("Product already exists");
}
// insert product
await db.collection("products").insertOne(product);
res.status(201).send("Product added successfully");
} catch (error) {
res.status(500).send("Server error");
}
});
// update product
app.put("/products/:id", async (req, res) => {
try {
const db = getdb();
const id = Number(req.params.id);
const updatedData = req.body;
// check if product exists
const existingProduct = await db
.collection("products")
.findOne({ id });
if (!existingProduct) {
return res.status(404).send("Product not found");
}
// update product
await db.collection("products").updateOne(
{ id },
{ $set: updatedData }
);
res.status(200).send("Product updated successfully");
} catch (error) {
res.status(500).send("Server error");
}
});
// delete product
app.delete("/products/:id", async (req, res) => {
try {
const db = getdb();
const id = Number(req.params.id);
// check if product exists
const existingProduct = await db
.collection("products")
.findOne({ id });
if (!existingProduct) {
return res.status(404).send("Product not found");
}
// delete product
await db.collection("products").deleteOne({ id });
res.status(200).send("Product deleted successfully");
} catch (error) {
res.status(500).send("Server error");
}
});