-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
96 lines (82 loc) · 2.65 KB
/
server.js
File metadata and controls
96 lines (82 loc) · 2.65 KB
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
var express= require('express'); //call for required models
var app= express(); //intializing app to use express
var bodyParser = require('body-Parser'); // intializing body-Parser
var mongoose = require('mongoose'); // intializing mongoose
app.use(bodyParser.urlencoded({extended:true}));
app.use(bodyParser.json());
var port = process.env.PORT || 8080;
mongoose.connect('mongodb://localhost:27017/deviceslistfinal2');
var Device= require('./app/models/Devices');
var router = express.Router(); //getting instance of express routing
router.use(function(req,res,next){
console.log("Something is happening"); //logging
next();
});
router.get('/',function(req,res){
res.json({message:'Welcome to our api'});
});
router.route('/Devices')
.post(function(req,res){
var device = new Device();
device.startSince =req.body.startSince;
device.suggestedValue = req.body.suggestedValue;
device.targetValue = req.body.targetValue;
device.currentStatus = req.body.currentStatus;
device.unit = req.body.unit;
device.switchBoolean = req.body.switchBoolean;
device.type= req.body.type;
device.name = req.body.name;
device.save(function(err){
if(err){
res.send(err);
res.json({message:'Error'});
}
else {
res.json({'message':'Device added', '_id':''+ device.id});
}
});
})
.get(function(req, res) {
Device.find(function(err, device) {
if (err)
res.send(err);
res.json(device);
});
});
router.route('/Devices/:device_id')
.get(function(req, res){
Device.findById(req.params.device_id,function(err,device){
if(err)
res.send(err);
res.json(device);
});
})
.put(function(req,res){
Device.findById(req.params.device_id, function(err, device){
if(err)
res.send(err);
device.startSince = req.body.startSince;
device.suggestedValue = req.body.suggestedValue;
device.targetValue = req.body.targetValue;
device.currentStatus = req.body.currentStatus;
device.unit = req.body.unit;
device.switchBoolean = req.body.switchBoolean;
device.type = req.body.type;
device.name = req.body.name;
device.save(function(err){
if(err)
res.send(err);
res.json({message:'Device Updated'});
});
});
})
.delete(function(req, res) {
Device.remove({_id: req.params.device_id},function(err, device) {
if (err)
res.send(err);
res.json({ message: 'Successfully deleted' });
});
});
app.use('/api',router); //all routes prefix with /api
app.listen(port); //start server
console.log('Magic Happens on port'+ port);