-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
80 lines (77 loc) · 2.54 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
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
const express = require('express');
const cors = require('cors')
const mysql = require ('mysql');
const app= express();
const selectAlltemperatures= "select id, unit_id, temperature,unix_timestamp from measurements order by unix_timestamp desc limit 5";
const averagetep ="select avg(temperature) as avg from measurements";
const connection=mysql.createConnection({
host: env.SERVER_IP,
user: env.USER,
password: env.PASS,
database: env.DB_NAME
});
connection.connect(err=>{
if(err){
throw console.log(err+" with connection");
}
else{
//console.log(connection.state)
}
});
app.use(cors());
//this function is used to list all values from db
app.get('/pushaverage',(req,res)=>{
connection.query(averagetep,(err,results)=>{
if (err){
throw res.send(err);
}
else{
return res.json({
data:results
})
}
});
});
//this function is used to list all values from db
app.get('/temperatures',(req,res)=>{
connection.query(selectAlltemperatures,(err,results)=>{
if (err){
throw res.send(err);
}
else{
return res.json({
data:results
})
}
});
});
//this function is used to add with parameters
app.get('/temperatures/add',(req,res)=>{
const {unitid,temp,timestamp}=req.query;
const instertemperature =`insert into measurements (unit_id,temperature,unix_timestamp) values('${unitid}','${temp}','${timestamp}')`;
connection.query(instertemperature,(err,results)=>{
if (err){
return res.send(err);
}
else{
return res.send('temperature added successfully')
}
});
});
//this function is used to update with parameters
app.get('/temperatures/update',(req,res)=>{
const {unitid,temp,timestamp}=req.query;
//const instertemperature =`update measurements set unit_id='${unitid}',temperature='${temp}',unix_timestamp='${timestamp}'where unit_id='${unitid}'`;
const instertemperature =`update measurements set temperature='${temp}'where id='${unitid}'`;
connection.query(instertemperature,(err,results)=>{
if (err){
return res.send(err);
}
else{
return res.send('temperature updated successfully')
}
});
});
app.listen(9000,()=>{
console.log(`mysql temperature dbserver connected and express server listening on port 9000`)
});