-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtil_web.js
91 lines (79 loc) · 2.42 KB
/
til_web.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
/*
Today I Learned webapp
*/
const assert = require("assert");
const FactStore = require("./lib/factStore");
const express = require("express");
const path = require("path");
const app = express();
const port = process.env.PORT || 5000;
app.use(express.json()); // all POST bodies are expected to be JSON
// Oops, probably shouldn't commit the database password
const dbUrl =
process.env.MONGODB_URI || "mongodb://til:[email protected]:21834/til";
const store = new FactStore(dbUrl);
app.get("/facts", getAll);
async function getAll(_request, response) {
let cursor = await store.all();
let output = [];
cursor.forEach(
entry => {
output.push(entry);
},
function(err) {
assert.equal(null, err);
console.log("Sending " + output.length + " records to client");
response.type("application/json").send(JSON.stringify(output));
}
);
}
app.post("/facts", addFact);
async function addFact(request, response) {
const { author, title, body } = request.body;
author.trim();
title.trim();
body.trim();
if (!title) throw "Title cannot be empty";
let result = await store.addFact(author, title, body);
let output = {
status: "ok",
id: result.id,
when: result.when
};
response.type("application/json").send(JSON.stringify(output));
}
app.delete("/facts", deleteFact);
async function deleteFact(request, response) {
const id = request.body.id;
const result = await store.deleteFact(id);
let output = {
status: "ok",
id: result.id
};
response.type("application/json").send(JSON.stringify(output));
}
app.post("/facts/:factId", editFact);
async function editFact(request, response) {
const { author, title, body } = request.body;
author.trim();
title.trim();
body.trim();
const id = request.params.factId;
const result = await store.editFact(id, author, title, body);
await console.log(result.status);
let output = {
status: "ok",
id: result.id
};
response.type("application/json").send(JSON.stringify(output));
}
// Serve React Files
if (process.env.NODE_ENV === "production") {
// Serve any static files
app.use(express.static(path.join(__dirname, "til-client/build")));
// Handle React routing, return all requests to React app
app.get("*", function(_request, response) {
response.sendFile(path.join(__dirname, "til-client/build", "index.html"));
});
}
app.listen(port, () => console.log(`TIL web app listening on port ${port}!`));