-
Notifications
You must be signed in to change notification settings - Fork 18
/
state-persistor.js
64 lines (53 loc) · 1.34 KB
/
state-persistor.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 http = require('http').Server(app);
const fs = require("fs").promises
const port = 8086
// to test POST with CURL:
// curl -X POST http://localhost:8086 -H "Content-Type: text/plain" -H "persistor-secret: hello" -d "content of the state"
// curl http://localhost:8086 -H "persistor-secret: hello" -o state.json
// to test persistor:
// npx cross-env PERSISTOR_SECRET=xxx nodemon state-persistor.js
app.use((req, res, next) =>
{
const secret = req.headers["persistor-secret"]
if (secret === process.env.PERSISTOR_SECRET)
next()
else
res.sendStatus(403)
})
app.get("/", async (req, res) =>
{
try
{
fs.readFile("persisted-state")
.then((state) => res.end(state))
.catch((err) =>
{
console.error(err)
res.sendStatus(500)
})
}
catch (e)
{
console.log(e)
res.sendStatus(500)
}
})
app.use(express.text({ limit: "5mb" }));
app.post("/", async (req, res) =>
{
try
{
const state = req.body
await fs.writeFile("persisted-state", state)
res.end()
}
catch (e)
{
console.log(e)
res.sendStatus(500)
}
})
http.listen(port, "0.0.0.0");
console.log("Server running on http://localhost:" + port);