-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
119 lines (104 loc) · 2.55 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
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
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
const express = require('express');
const app = express();
const http = require('http');
const https = require('https');
const Sequelize = require('sequelize');
require('dotenv').config();
const SECRET = process.env.SECRET;
const DB_HOST = process.env.DB_HOST;
const DB_USER = process.env.DB_USER;
const DB_PASS = process.env.DB_PASS;
const DB_NAME = process.env.DB_NAME;
const APP_PORT = process.env.APP_PORT;
app.set('view engine', 'pug');
app.use(express.static('public'));
app.use(express.json());
let Temperature = null;
const sequelize = new Sequelize(DB_NAME, DB_USER, DB_PASS, {
host: DB_HOST,
dialect: 'mysql',
pool: {
max: 5,
min: 0,
acquire: 50000,
idle: 10000
},
});
function initDB() {
sequelize
.authenticate()
.then(() => {
console.log("Successfully connected to DB");
Temperature = sequelize.define('temperature', {
time: Sequelize.DATE,
temperature: Sequelize.FLOAT
});
})
.catch((e) => {
console.log("Failed connection to DB with error:", e);
setTimeout(function () {
initDB();
}, 10000)
});
}
initDB();
app.get('/', async (req, res) => {
const allData = await Temperature.findAll({
order: [
['time', 'ASC']
]
})
.catch(() => {
return [];
});
const lastFiveDaysData = await Temperature.findAll({
where: {
time: {
[Sequelize.Op.gt]: new Date(new Date() - 24*60*60*1000*5)
}
},
order: [
['time', 'ASC']
]
}).catch(() => {
return [];
});
res.render('index', {
temperatureData: allData,
lastFiveDays: lastFiveDaysData
});
});
app.post('/temperature', function (req, res) {
if (req.body && req.body.secret && req.body.data) {
const isValidPassPhrase = req.body.secret === SECRET;
if (!isValidPassPhrase) {
console.error('Invalid passphrase provided:', req.body.secret);
res.send({
'success': false,
'message': 'Invalid passphrase provided',
});
return;
}
var temperatures = req.body.data.map((temp) => {
return {
temperature: temp.temperature,
time: temp.time,
}
});
temperatures.forEach((temp) => {
sequelize.sync()
.then(() => Temperature.create({
time: temp.time,
temperature: temp.temperature
}));
});
}
res.send({
'success': true
});
});
const httpServer = http.createServer(app);
httpServer.listen(APP_PORT, () => {
console.log("htttp server running at port " + APP_PORT);
});
// TODO: Fix httpsServer together with letsencrypt