-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
92 lines (78 loc) · 2.57 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
// Configure environment variables.
require('dotenv').config();
// Imports.
const express = require('express');
const bodyParser = require('body-parser');
const Keyv = require('keyv')
const KeyvFile = require('keyv-file').KeyvFile
// Set up our file-based key-value storage.
const storage = new Keyv({
store: new KeyvFile({
filename: `data-storage.json`
})
});
// Application setup.
const app = express();
app.use(express.static('static'));
app.set('view engine', 'ejs');
app.use(bodyParser.json({ limit: '50mb' }));
app.use(bodyParser.urlencoded({ limit: '50mb', extended: true }));
// Parsing out environment variables.
const APPLICATION = process.env.APPLICATION;
const PORT = process.env.PORT;
const SECRET = process.env.SECRET;
// A helper function to sleep asynchronously.
const sleep = function (ms) {
return new Promise(resolve => setTimeout(resolve, ms));
};
// A middleware for validating POST requests from the master computer.
const verifyPostData = function (req, res, next) {
const requestSecret = req.body.secret;
if (requestSecret !== SECRET) {
return next(`Request body secret mismatch!`);
}
return next();
};
// A middleware for validating GET requests from the master computer.
const verifyGetData = function (req, res, next) {
const requestSecret = req.header('secret');
if (requestSecret !== SECRET) {
return next(`Request header secret mismatch!`);
}
return next();
};
// Allow verified sources to push data to the persistence layer.
app.post('/put', verifyPostData, async function (req, res) {
const key = req.body.key;
const value = req.body.value;
try {
await storage.set(key, value);
// Catch any errors that might occur in storing data.
} catch (error) {
console.error(error);
res.status(400).send(error);
}
// Tell master computer that we've completed the request.
res.status(200).send({ message: 'Putting data succeeded.' });
});
// Allow verified sources to get data from the persistence layer.
app.get('/get/:key', verifyGetData, async function (req, res) {
const key = req.params.key;
try {
let value = await storage.get(key);
res.status(200).send({ value: value });
// Catch any errors that might occur in storing data.
} catch (error) {
console.error(error);
res.status(400).send(error);
}
});
// Use a middleware that allows us to authenticate incoming requests.
app.use((err, req, res, next) => {
if (err) console.error(err);
res.status(403).send('Request authentication failed.');
});
// Launch the application and begin the server listening.
app.listen(PORT, function () {
console.log(APPLICATION, 'listening on port', PORT);
});