-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathserver.js
95 lines (76 loc) · 2.28 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
var express = require('express');
var bodyParser = require('body-parser');
var cors = require('cors');
var app = express();
var mongoose = require('mongoose');
var product = require('./product');
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
var port = process.env.PORT || 8090;
var router = express.Router();
mongoose.connect('mongodb://localhost:27017/products');
// Middle Route
router.use(function (req, res, next) {
// do logging
// do authentication
console.log('Logging of request will be done here');
next(); // make sure we go to the next routes and don't stop here
});
router.route('/products').post(function (req, res) {
console.log("in add");
var p = new product();
p.title = req.body.title;
p.price = req.body.price;
p.instock = req.body.instock;
p.photo = req.body.photo;
p.save(function (err) {
if (err) {
res.send(err);
}
console.log("added");
res.send({ message: 'Product Created !' })
})
});
router.route('/products').get(function (req, res) {
product.find(function (err, products) {
if (err) {
res.send(err);
}
res.send(products);
});
});
router.route('/products/:product_id').get(function (req, res) {
product.findById(req.params.product_id, function (err, prod) {
if (err)
res.send(err);
res.json(prod);
});
});
router.route('/products/:product_id').put(function (req, res) {
product.findById(req.params.product_id, function (err, prod) {
if (err) {
res.send(err);
}
prod.title = req.body.title;
prod.price = req.body.price;
prod.instock = req.body.instock;
prod.photo = req.body.photo;
prod.save(function (err) {
if (err)
res.send(err);
res.json({ message: 'Product updated!' });
});
});
});
router.route('/products/:product_id').delete(function (req, res) {
product.remove({ _id: req.param.product_id }, function (err, prod) {
if (err) {
res.send(err);
}
res.json({ message: 'Successfully deleted' });
})
});
app.use(cors());
app.use('/api', router);
app.listen(port);
console.log('REST API is runnning at ' + port);