-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
53 lines (45 loc) · 1.34 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
// Create express app
var express = require("express")
var app = express()
var db = require("./database.js")
// Server port
var HTTP_PORT = 8000
// Start server
app.listen(HTTP_PORT, () => {
console.log("Server running on port %PORT%".replace("%PORT%", HTTP_PORT))
});
// Root endpoint
app.get("/", (req, res, next) => {
res.json({ "message": "Ok" })
});
// Headers
app.all('/*', function (req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "X-Requested-With, Content-Type");
res.header("Access-Control-Allow-Methods", "GET, POST", "PUT");
next();
});
/**
* Returns battery data for given tag mac address
*/
app.get("/api/tag/:mac/battery", (req, res, next) => {
console.log('battery status', req.originalUrl);
var sql = "SELECT battery FROM sensors WHERE mac = ? ORDER BY timestamp DESC LIMIT 1"
var params = [req.params.mac]
db.all(sql, params, (err, rows) => {
if (err) {
console.error(err.message);
res.status(400).json({ "error": err.message });
return;
}
console.log(">>> success", rows);
res.json({
"message": "success",
"data": rows[0].battery
})
});
});
// Default response for any other request
app.use(function (req, res) {
res.status(404);
});