-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
105 lines (85 loc) · 2.63 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
// Add the required dependencies
var restify = require('restify');
var mongojs = require('mongojs');
//add the db config, for local use var db = mongojs('productsdb', ['products']);
var db = mongojs('mongodb://admin:[email protected]:41841/restifymyapp', ['products']);
// Create a new server and start it
var server = restify.createServer();
server.use(restify.acceptParser(server.acceptable));
server.use(restify.queryParser());
server.use(restify.bodyParser());
// Start listening to any free port
server.listen(3000, function () {
console.log("Server started @ 3000");
});
// GET – All Products
server.get("/products", function (req, res, next) {
db.products.find(function (err, products) {
res.writeHead(200, {
'Content-Type': 'application/json; charset=utf-8'
});
res.end(JSON.stringify(products));
});
return next();
});
//POST – Add New Product
server.post('/product', function (req, res, next) {
var product = req.params;
db.products.save(product, function (err, data) {
res.writeHead(200, {
'Content-Type': 'application/json; charset=utf-8'
});
res.end(JSON.stringify(data));
});
return next();
});
server.put('/product/:id', function (req, res, next) {
// get the existing product
db.products.findOne({
id: req.params.id
}, function (err, data) {
// merge req.params/product with the server/product
var updProd = {}; // updated products
// logic similar to jQuery.extend(); to merge 2 objects.
for (var n in data) {
updProd[n] = data[n];
}
for (var n in req.params) {
updProd[n] = req.params[n];
}
db.products.update({
id: req.params.id
}, updProd, {
multi: false
}, function (err, data) {
res.writeHead(200, {
'Content-Type': 'application/json; charset=utf-8'
});
res.end(JSON.stringify(data));
});
});
return next();
});
server.del('/product/:id', function (req, res, next) {
db.products.remove({
id: req.params.id
}, function (err, data) {
res.writeHead(200, {
'Content-Type': 'application/json; charset=utf-8'
});
res.end(JSON.stringify(true));
});
return next();
});
server.get('/product/:id', function (req, res, next) {
db.products.findOne({
id: req.params.id
}, function (err, data) {
res.writeHead(200, {
'Content-Type': 'application/json; charset=utf-8'
});
res.end(JSON.stringify(data));
});
return next();
});
module.exports = server;