forked from froeba/workshop-web-app
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.ts
84 lines (77 loc) · 2.34 KB
/
index.ts
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
import express from "express";
import { ConnectApi } from "mbed-cloud-sdk";
import { NotificationData } from "mbed-cloud-sdk/types/legacy/connect/types";
import moment from "moment";
import path from "path";
import { Pool } from "pg";
import { setup } from "./src/setup";
const PORT = process.env.PORT || 5000;
const connect = new ConnectApi({
forceClear: true,
autostartNotifications: false,
});
const pool = new Pool({
connectionString: process.env.DATABASE_URL,
ssl: true,
});
interface Results {
results: any[];
}
const getQuery = async (query = "select * from resource_values;") => {
const results: Results = { results: [] };
const client = await pool.connect();
const result = await client.query(query);
results.results = result ? result.rows : [];
client.release();
return results;
};
const notification = async ({ deviceId, path, payload }: NotificationData) => {
if (isNaN(payload as number)) {
return;
}
const text =
"INSERT INTO resource_values(device_id, path, time, value) VALUES($1, $2, to_timestamp($3 / 1000.0), $4) RETURNING *";
const values = [deviceId, path, Date.now(), payload];
try {
const res = await pool.query(text, values);
const { id, device_id, path, value, time } = res.rows[0];
const t = moment(time)
.format("lll")
.toString();
console.log(`${t} ${id} ${device_id} ${path} ${value}`);
} catch (err) {
console.log(err.stack);
}
};
express()
.use(express.static(path.join(__dirname, "client/build")))
.use(express.json())
.use((req, res, next) => {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
})
.get("/values", async (req, res) => {
const query = "select * from resource_values order by time desc limit 10000;";
try {
res.send(await getQuery(query));
} catch (err) {
res.send("Error" + err);
}
})
.all("/callback", async (req, res) => {
try {
connect.notify(req.body);
} catch (err) {
console.log(err.stack);
} finally {
res.sendStatus(204);
}
})
.get("*", (req, res) => {
res.sendFile(path.join(__dirname + "/client/build/index.html"));
})
.listen(PORT, () => console.log(`Listening on ${PORT}`))
.once("listening", () => {
setup(connect, pool, notification);
});