-
Notifications
You must be signed in to change notification settings - Fork 19
/
Server.js
97 lines (91 loc) · 3.26 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
var express = require("express");
var app = express();
var bodyParser = require("body-parser");
var mongoOp = require("./models/mongo");
var router = express.Router();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({"extended" : false}));
router.get("/",function(req,res){
res.json({"error" : false,"message" : "Hello World"});
});
router.route("/users")
.get(function(req,res){
var response = {};
mongoOp.find({},function(err,data){
if(err) {
response = {"error" : true,"message" : "Error fetching data"};
} else {
response = {"error" : false,"message" : data};
}
res.json(response);
});
})
.post(function(req,res){
var db = new mongoOp();
var response = {};
db.userEmail = req.body.email;
db.userPassword = require('crypto').createHash('sha1').update(req.body.password).digest('base64');
db.save(function(err){
if(err) {
response = {"error" : true,"message" : "Error adding data"};
} else {
response = {"error" : false,"message" : "Data added"};
}
res.json(response);
});
});
router.route("/users/:id")
.get(function(req,res){
var response = {};
mongoOp.findById(req.params.id,function(err,data){
if(err) {
response = {"error" : true,"message" : "Error fetching data"};
} else {
response = {"error" : false,"message" : data};
}
res.json(response);
});
})
.put(function(req,res){
var response = {};
mongoOp.findById(req.params.id,function(err,data){
if(err) {
response = {"error" : true,"message" : "Error fetching data"};
} else {
if(req.body.userEmail !== undefined) {
data.userEmail = req.body.userEmail;
}
if(req.body.userPassword !== undefined) {
data.userPassword = req.body.userPassword;
}
data.save(function(err){
if(err) {
response = {"error" : true,"message" : "Error updating data"};
} else {
response = {"error" : false,"message" : "Data is updated for "+req.params.id};
}
res.json(response);
})
}
});
})
.delete(function(req,res){
var response = {};
mongoOp.findById(req.params.id,function(err,data){
if(err) {
response = {"error" : true,"message" : "Error fetching data"};
} else {
mongoOp.remove({_id : req.params.id},function(err){
if(err) {
response = {"error" : true,"message" : "Error deleting data"};
} else {
response = {"error" : true,"message" : "Data associated with "+req.params.id+"is deleted"};
}
res.json(response);
});
}
});
})
app.use('/',router);
app.listen(3000);
console.log("Listening to PORT 3000");