-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
64 lines (52 loc) · 1.45 KB
/
app.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
const express = require('express');
const app = express();
const db = require('./config/db.js');
const port = process.env.PORT || 3000;
const http = require('http');
const bodyParser = require('body-parser');
const server = http.createServer(app);
const { Server } = require("socket.io");
const io = new Server(server);
//body parser middleware
app.use(bodyParser.json());
//setting static folder
app.use(express.static('assets'));
app.get('/dashboard', (req, res) => {
res.sendFile(__dirname + '/index.html');
});
app.get('/getState',(req, res)=>{
db.query('SELECT * FROM nodes', (err, data)=>{
if(err) throw err;
res.send(JSON.stringify(data));
});
});
app.post('/api/v1/updateState',(req, res)=>{
let body = req.body;
console.log(body);
if(Object.keys(body).length != 2 ){
res.send('{"status":"error"}\n');
}
else{
db.query('SELECT * FROM nodes WHERE nodeId = ?', body.nodeId,(err, data)=>{
if(data.length != 0){
db.query('UPDATE nodes SET state = ? WHERE nodeId = ?',[body.state, body.nodeId],(err, data)=>{
if(err) throw err;
io.emit('state update', {message:'this is a test'});
res.send('{"status":"success"}\n');
});
}
else{
res.send('{"status":"error"}\n');
}
});
}
});
io.on('connection', (socket) => {
console.log('a user connected');
socket.on('disconnect', () => {
console.log('a user disconnected');
});
});
server.listen(port, () => {
console.log(`Server listening at port ${port}`);
});