-
Notifications
You must be signed in to change notification settings - Fork 4
/
management.js
118 lines (101 loc) · 2.66 KB
/
management.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
/* eslint-disable no-console */
const config = require("config");
const express = require("express");
const chalk = require("chalk");
const bodyParser = require("body-parser");
const yarn = require("yarn-api");
const pm2 = require("pm2");
const util = require("util");
const yarnPromise = util.promisify(yarn);
const jsonParser = bodyParser.json();
console.log(chalk.yellow("Starting Thinglator management API"));
// load and initialise express
const app = express();
const delay = t =>
new Promise(resolve => {
setTimeout(resolve, t);
});
const pm2Restart = packageId =>
new Promise((resolve, reject) => {
pm2.restart(packageId, (err, apps) => {
if (err) {
reject(err);
return;
}
resolve(apps);
});
});
const pm2GetInfo = packageId =>
new Promise((resolve, reject) => {
pm2.describe(packageId, (err, describeInfo) => {
if (err) {
reject(err);
return;
}
resolve(describeInfo);
});
});
const installDriver = async driverId => {
await yarnPromise(["add", `thinglator-driver-${driverId}`]);
await pm2Restart(config.get("pm2.thinglatorId"));
await delay(3000);
const info = await pm2GetInfo(config.get("pm2.thinglatorId"));
if (info[0].pm2_env.unstable_restarts > 0) {
throw new Error("Install failed");
}
};
const uninstallDriver = async driverId => {
await yarnPromise(["remove", `thinglator-driver-${driverId}`]);
await pm2Restart(config.get("pm2.thinglatorId"));
await delay(3000);
const info = await pm2GetInfo(config.get("pm2.thinglatorId"));
if (info[0].pm2_env.unstable_restarts > 0) {
throw new Error("Install failed");
}
};
// setup the HTTP API
app.get("/", (req, res) => {
res.json({
"Thinglator Management": "Oh, hi!"
});
});
app.post("/install", jsonParser, async (req, res) => {
try {
const body = req.body;
if (!body.driverId) {
throw new Error("driverId not specified");
}
await installDriver(body.driverId);
res.json({ success: true });
} catch (err) {
res.status(400);
console.error(err);
res.json({
message: err.message
});
}
});
app.post("/uninstall", jsonParser, async (req, res) => {
try {
const { body } = req;
if (!body.driverId) {
throw new Error("driverId not specified");
}
await uninstallDriver(body.driverId);
res.json({ success: true });
} catch (err) {
res.status(400);
console.error(err);
res.json({
message: err.message
});
}
});
// Initialise the webserver
app.listen(config.get("management.port"), () => {
console.log(
chalk.blue(
`REST API server listening on port ${config.get("management.port")}`
)
);
});