-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.ts
53 lines (48 loc) · 1.44 KB
/
index.ts
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
import express, { Request, Response } from "express";
import Mustache from "mustache";
import { readFile } from "fs/promises";
import bodyParser from "body-parser";
const app = express();
const port = 3000;
const comments: { author: string; comment: string }[] = [];
app.use(bodyParser.json()); // to support JSON-encoded bodies
app.use(
bodyParser.urlencoded({
// to support URL-encoded bodies
extended: true,
}),
);
app.get("/", async (req: Request, res: Response) => {
const [layoutTpl, blogTpl, newCommentTpl, commentsTpl] = await Promise.all([
readFile("partials/layout.mustache", { encoding: "utf8" }),
readFile("partials/blog.mustache", { encoding: "utf8" }),
readFile("partials/new-comment.mustache", { encoding: "utf8" }),
readFile("partials/comments.mustache", { encoding: "utf8" }),
]);
const body = Mustache.render(blogTpl, {
content: "contents here",
newComment: newCommentTpl,
comments: Mustache.render(commentsTpl, {
comments,
}),
});
const page = Mustache.render(layoutTpl, {
body,
});
res.send(page);
});
app.post("/blog/new-comment", async (req: Request, res: Response) => {
const author = req.body.author;
const comment = req.body.comment;
comments.push({
author,
comment,
});
const [newCommentTpl] = await Promise.all([
readFile("partials/new-comment.mustache", { encoding: "utf8" }),
]);
res.send(newCommentTpl);
});
app.listen(port, () => {
console.log(`Example app listening on port ${port}`);
});