forked from austintackaberry/stocks
-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
83 lines (74 loc) · 2.13 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
const express = require("express");
const helmet = require("helmet");
const path = require("path");
const fs = require("fs");
var uuidv4 = require("uuid/v4");
const app = express();
const port = process.env.PORT || 5000;
const AWS = require("aws-sdk");
require("dotenv").config();
app.use(helmet());
app.use(function(req, res, next) {
res.locals.nonce = uuidv4();
next();
});
app.use(
helmet.contentSecurityPolicy({
directives: {
defaultSrc: ["'self'"],
scriptSrc: ["'self'", "https://www.google-analytics.com/analytics.js"],
imgSrc: ["'self'", "https://www.google-analytics.com"],
styleSrc: [
"'self'",
function(req, res) {
return "'nonce-" + res.locals.nonce + "'";
}
]
}
})
);
// Only serve up static build files in production
if (process.env.NODE_ENV === "production") {
app.get("/", async function(req, res) {
const pagePath = path.join(__dirname + "/client/build/index.html");
let html = await getHtml(pagePath);
html = html
.replace(/<script/g, `<script nonce="${res.locals.nonce}"`)
.replace(/<style/g, `<style nonce="${res.locals.nonce}"`);
res.send(html);
});
app.use(express.static("client/build"));
}
app.get("/getStockData", async (req, res) => {
AWS.config.update({
region: "us-west-1"
});
const dynamodb = new AWS.DynamoDB.DocumentClient({
apiVersion: "2012-08-10",
accessKeyId: process.env.AWS_ACCESS_KEY_ID,
secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY,
region: "us-west-1"
});
const params = {
TableName: "stockit"
};
// Get all documents from db and randomly choose one
dynamodb.scan(params, (err, data) => {
if (err) {
console.log(err);
} else {
const count = data.Count;
const randId = Math.floor(Math.random() * count);
const item = data.Items[randId];
res.send(item);
}
});
});
app.listen(port, () => console.log(`Server listening on port ${port}`));
const getHtml = path =>
new Promise((resolve, reject) =>
fs.readFile(path, "utf-8", (err, contents) => {
if (err) return reject(err);
return resolve(contents);
})
);