forked from nourbenamor201/lab_assignment
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
73 lines (62 loc) · 1.7 KB
/
app.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
const express = require('express');
const connectDB = require("./db");
const Product = require('./product');
const cors = require('cors');
const app = express();
app.use(express.json());
app.use(cors());
connectDB();
app.get('/products', async (req,res)=>{
try {
const products = await Product.find();
res.json(products);
}
catch (error){
res.status(500).send(error.message);
}
})
app.get('/products/:id', async (req,res)=>{
try {
const product = await Product.findById(req.params.id);
if (!product) throw new Error('Product not found');
res.json(product);
}
catch (error){
res.status(500).send(error.message);
}
});
app.post('/products', async (req,res)=>{
try {
const {name, price, quantity} = req.body;
const product = new Product({name, price, quantity});
await product.save();
res.json({success:true});
}
catch (error){
res.status(500).send(error.message);
}
});
app.put('/products/:id', async (req,res)=>{
try {
const product = await Product.findByIdAndUpdate(req.params.id, req.body, {new:true});
if (!product) throw new Error('Product not found');
res.json({success:true});
}
catch (error){
res.status(500).send(error.message);
}
});
app.delete('/products/:id', async (req,res)=>{
try {
const product = await Product.findByIdAndDelete(req.params.id);
if (!product) throw new Error('Product not found');
res.json({success:true});
}
catch (error){
res.status(500).send(error.message);
}
});
const port = 5000;
app.listen(port, ()=>{
console.log("API server started on port 5000");
})