-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
90 lines (78 loc) · 2.02 KB
/
index.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
const express = require("express");
const bodyParser = require("body-parser");
const AWS = require("aws-sdk");
const ddb = new AWS.DynamoDB({ apiVersion: "2012-08-10" });
const app = express();
const port = process.env.PORT || 8000;
const environment = process.env.ENVIRONMENT
? process.env.ENVIRONMENT
: "not informed";
const table = process.env.TABLE ? process.env.TABLE : "environment";
const region = process.env.REGION ? process.env.REGION : "us-east-1";
AWS.config.update({ region: region });
console.log("ENVIRONMENT: ", environment);
console.log("TABLE: ", table);
console.log("REGION: ", region);
app.use(bodyParser.json());
app.get("/", (req, res) => {
console.info("root route");
res.send(process.env.API_WORKS_MESSAGE);
});
app.get("/api/environment", (req, res) => {
console.info("environment data route");
res.json([
{
environment: `${environment}`,
},
]);
});
app.get("/api/data", (req, res) => {
console.info("api data GET route");
const params = {
TableName: table,
Key: {
environment: { N: environment },
},
ProjectionExpression: "createdAt",
};
ddb.getItem(params, function (err, data) {
if (err) {
res.json(err);
} else {
res.json(data.Item);
}
});
});
app.post("/api/data", (req, res) => {
console.info("api data POST route");
const date = new Date().toISOString().replace(/T/, " ").replace(/\..+/, "");
const params = {
TableName: table,
Key: {
environment: { N: environment },
},
UpdateExpression: "SET #postedAt = :postedAt",
ExpressionAttributeNames: {
"#postedAt": "postedAt",
},
ExpressionAttributeValues: {
":postedAt": {
S: date,
},
},
ReturnValues: "NONE",
};
ddb.updateItem(params, function (err, data) {
if (err) {
res.json(err);
} else {
res.json(`Inserted "${date}" at environment ${environment}`);
}
});
});
app.listen(port, (err) => {
if (err) {
console.error("Error:", err);
}
console.info(`Listening port ${port}`);
});