-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathroutes.js
103 lines (80 loc) · 3.42 KB
/
routes.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
// app/routes.js
// grab the nerd model we just created
var Routine = require('./models/routine');
module.exports = function(app) {
var sonosJson = {};
var openConnections = [];
app.get('/api/routines', function(req, res) {
// use mongoose to get all routines in the database
Routine.find(function(err, routines) {
// if there is an error retrieving, send the error.
// nothing after res.send(err) will execute
if (err)
res.send(err);
res.json(routines); // return all routines in JSON format
});
});
// route to handle creating goes here (app.post)
app.post('/api/routines', function (req, res) {
var routine = new Routine();
routine.name = req.body.name;
routine.hour = req.body.hour;
routine.minute = req.body.minute;
routine.dayOfWeek = req.body.dayOfWeek;
routine.message = req.body.message;
routine.getWeather = req.body.getWeather;
routine.getQotd = req.body.getQotd;
console.log('routine = ' + routine);
routine.save(function(err, routine) {
if (err) return console.error(err);
res.json({ message: 'routine created!'});
});
});
// route to handle delete goes here (app.delete)
app.delete('/api/routines/:routine_id', function(req, res) {
Routine.remove({
_id: req.params.routine_id}, function(err,bear) {
if (err)
res.send(err);
res.json({ message: 'successfully deleted'});
});
});
app.get('/sonosChange', function (req, res) {
// set timeout as high as possible
req.socket.setTimeout(Number.MAX_VALUE);
res.writeHead(200, {
'Content-Type': 'text/event-stream',
'Cache-Control': 'no-cache',
'Connection': 'keep-alive'
});
console.log("opening event source connection");
openConnections.push(res);
});
function constructSSE() {
console.log('constructing sse');
if (openConnections.length > 0) {
if (sonosJson) {
console.log(sonosJson);
openConnections[0].write('\n');
openConnections[0].write('data: ' + JSON.stringify(sonosJson) + '\n\n');
}
}
}
app.post('/sonos', function (req, res) {
console.log("just received message from sonos");
if (req.body.type == 'transport-state') {
console.log('updating sonos json');
sonosJson = req.body.data.state.currentTrack;
constructSSE();
}
res.sendStatus(200);
})
// frontend routes =========================================================
// route to handle all angular requests
// NOTE: you need to place other HTTP requests above this since this is a catch all and will
// re-route all your requests to the home page.
app.get('*', function(req, res) {
console.log("serving up view index.html");
res.sendFile('/public/index.html', { root : __dirname}); // load our public/index.html file
});
};