-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
111 lines (91 loc) · 2.16 KB
/
server.js
File metadata and controls
111 lines (91 loc) · 2.16 KB
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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
const path = require("path");
const express = require("express");
const bodyParser = require("body-parser");
const cors = require("cors");
const sqlite = require("sqlite3");
const unflatten = require("flat").unflatten;
const dbFilePath = path.join(__dirname, "dev.db");
const db = new sqlite.Database(dbFilePath, sqlite.OPEN_READWRITE);
const app = express();
app.use(bodyParser.json());
app.use(
cors({
origin: "*",
})
);
const ALL_USERS_QUERY = `
SELECT *
FROM user;
`;
app.get("/users", async (req, res, next) => {
db.all(ALL_USERS_QUERY, (err, users) => {
if (err) {
next(err);
}
res.json(users);
});
});
const ALL_COMMENTS_QUERY = `
SELECT c.*, u.id as 'user.id', u.name as 'user.name'
FROM comment c JOIN user u ON c.user_id = u.id
`;
const ALL_REPLY_QUERY = `
SELECT r.* ,c.id as 'comment_id'
FROM reply r JOIN comment c ON r.comment_id = c.id
`;
app.get("/comments", async (req, res, next) => {
db.all(ALL_COMMENTS_QUERY, (err, rows) => {
if (err) {
next(err);
}
const comments = rows.map(unflatten);
res.json(comments);
});
});
const INSERT_COMMENT_QUERY = `
INSERT INTO comment
(content, user_id)
VALUES
(?, ?);
`;
const INSERT_REPLY_QUERY = `
INSERT INTO reply
(content, user_id,comment_id)
VALUES
(?, ?,?);
`;
app.post("/comments", (req, res, next) => {
const { user_id, content } = req.body;
db.run(INSERT_COMMENT_QUERY, [content, user_id], (err) => {
if (err) {
next(err);
}
res.sendStatus(204);
});
});
app.post("/reply", (req, res, next) => {
const { user_id,comment_id, content } = req.body;
db.run(INSERT_REPLY_QUERY, [content, user_id,comment_id], (err) => {
if (err) {
next(err);
}
res.sendStatus(204);
});
});
app.get("/reply", async (req, res, next) => {
db.all(ALL_REPLY_QUERY, (err, rows) => {
if (err) {
next(err);
}
const comments = rows.map(unflatten);
res.json(comments);
});
});
app.use((err, req, res, next) => {
console.error(err);
res.status(500).json({ error: err.toString() });
});
const PORT = process.env.PORT || 3001;
app.listen(PORT, () => {
console.log(`Server ready at http://localhost:3001`);
});