-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
104 lines (86 loc) · 2.37 KB
/
server.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
96
97
98
99
100
101
102
103
104
// passwaord: adminNodeApi
const express = require("express");
const mongoose = require("mongoose");
const Product = require("./models/productModel");
const app = express();
app.use(express.json());
// routes
app.get("/", (req, res) => {
res.send("Hello NODE API");
});
app.get("/products", async (req, res) => {
try {
const product = await Product.find({});
res.status(200).json(product);
} catch (error) {
console.log(error);
res.status(500).json({ message: error.message });
}
});
app.get("/products/:id", async (req, res) => {
try {
const { id } = req.params;
const product = await Product.findById(id);
res.status(200).json(product);
} catch (error) {
console.log(error);
res.status(500).json({ message: error.message });
}
});
app.post("/product", async (req, res) => {
try {
const product = await Product.create(req.body);
res.status(200).json(product);
} catch (error) {
console.log(error.message);
res.status(500).json({ message: error.message });
}
});
// update a product
app.put("/products/:id", async (req, res) => {
try {
const { id } = req.params;
const product = await Product.findByIdAndUpdate(id, req, body);
// no product found in DB
if (!product) {
return res
.status(400)
.json({ message: `cannot fund any profuct with ID ${id}` });
}
const updatedProduct = await Product.findById(id);
res.status(200).json(updatedProduct);
} catch (error) {
console.log(error.message);
res.status(500).json({ message: error.message });
}
});
// delete a product
app.delete("/product/:id", async (req, res) => {
try {
const { id } = req.params;
const product = await Product.findByIdAndDelete(id);
if (!product) {
return res
.status(404)
.json({ message: `cannot find any product with ID ${id}` });
}
res.status(200).json(product);
} catch (error) {
console.log(error.message);
res.status(500).json({ message: error.message });
}
});
mongoose.set("strictQuery", false);
mongoose
.connect(
"mongodb+srv://vasilis123:admin123@nodeapi.zeglunh.mongodb.net/node-API?retryWrites=true&w=majority"
)
.then(() => {
console.log("connected to MongoDB");
app.listen(3001, () => {
console.log(`Node API app is running on port 3001`);
});
})
.catch((error) => {
console.log(error);
});