/
app.js
200 lines (186 loc) · 6.72 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
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
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
const express = require("express");
const hbs = require("express-handlebars");
const { ObjectId } = require("mongodb");
const crypto = require("./utils/crypto")
const mongodbConnection = require("./configs/mongodb-connection");
const postService = require("./services/post-service");
const app = express();
const port = 3000
let collection;
// 서버 실행 및 MongoDB 연결
app.listen(port, async () => {
console.log("Server started on", port);
const mongoClient = await mongodbConnection();
collection = mongoClient.db().collection("post");
});
// Handlebars를 뷰 엔진으로 설정
app.engine("hbs", hbs.create({ helpers: require("./configs/hbs-helpers"), }).engine);
app.set("view engine", "hbs");
app.set("views", __dirname + "/views");
// 정적파일, JSON, URL-encoded 데이터 파싱
app.use("/views/styles", express.static(__dirname + "/views/styles"));
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
// 홈 페이지 요청 처리
app.get("/", async (req, res) => {
const page = parseInt(req.query.page) || 1; // 페이지 번호 파라미터 또는 기본값 1
const search = req.query.search || ""; // 검색어 파라미터 또는 빈 문자열
try {
const [posts, paginator] = await postService.list(collection, page, search);
res.render("home", { search, paginator, posts });
} catch (error) {
console.error(error);
res.render("home");
}
});
// 게시글 작성 페이지 요청 처리
app.get("/write", (req, res) => { res.render("write", { mode: "create" }); });
// 게시글 작성 처리
app.post("/write", async (req, res) => {
const post = req.body;
try {
encryptedPassword = await crypto.encryptPassword(post.password)
const postWithEncryptedPassword = { ...post, password: encryptedPassword };
const result = await postService.writePost(collection, postWithEncryptedPassword);
res.redirect(`/detail/${result.insertedId}`);
} catch (error) {
console.log(error);
res.render("home");
}
});
// 게시글 상세 보기 페이지 요청 처리
app.get("/detail/:id", async (req, res) => {
try {
const result = await postService.getDetailPost(collection, req.params.id);
if (!result) { res.render("home"); }
res.render("detail", { post: result.value, });
} catch (error) {
console.log(error);
res.render("home")
}
});
// 패스워드 확인 처리
app.post("/check-password", async (req, res) => {
const { id, password } = req.body;
try {
const post = await postService.getPostById(collection, id);
const match = await crypto.comparePasswords(password, post.password)
if (!match) { return res.status(404).json({ isExist: false }); }
return res.json({ isExist: true });
} catch (error) {
console.log(error);
res.render("home")
}
});
// 게시글 수정 페이지 요청 처리
app.get("/modify/:id", async (req, res) => {
const { id } = req.params.id;
try {
const post = await postService.getPostById(collection, req.params.id);
if (!post) { return res.render("home") }
res.render("write", { mode: "modify", post });
} catch (error) {
console.log(error);
res.render("home")
}
});
// 게시글 수정 처리
app.post("/modify/", async (req, res) => {
const { id, title, writer, password, content } = req.body;
try {
const post = await postService.getPostById(collection, id);
const match = await crypto.comparePasswords(password, post.password)
if (!match) { return res.redirect(`/detail/${id}`); }
const checkpost = {
title,
writer,
password: post.password,
content
};
const result = await postService.updatePost(collection, id, checkpost);
res.redirect(`/detail/${id}`);
} catch (error) {
console.log(error)
res.redirect(`/detail/${id}`);
}
});
// 게시글 삭제 처리
app.delete("/delete", async (req, res) => {
const { id, password } = req.body;
try {
const post = await postService.getPostById(collection, id);
const match = await crypto.comparePasswords(password, post.password)
if (!match) { res.status(404) }
const result = await collection.deleteOne({ _id: new ObjectId(id), password: post.password, });
if (result.deletedCount !== 1) {
console.log("삭제실패");
return res.json({ isSuccess: false });
}
return res.json({ isSuccess: true });
} catch (error) {
console.error(error);
return res.json({ isSuccess: false });
}
});
// 댓글 작성 처리
app.post("/write-comment", async (req, res) => {
const { id, name, password, comment } = req.body;
const encryptedPassword = await crypto.encryptPassword(password)
const post = await postService.getPostById(collection, id);
if (post.comments) {
post.comments.push({
idx: post.comments.length + 1,
name,
password: encryptedPassword,
comment,
createdDt: new Date().toISOString(),
});
} else {
post.comments = [
{
idx: 1,
name,
password: encryptedPassword,
comment,
createdDt: new Date().toISOString(),
},
];
}
postService.updatePost(collection, id, post);
return res.redirect(`/detail/${id}`);
});
// 댓글 삭제 처리
app.delete("/delete-comment", async (req, res) => {
const { id, idx, password } = req.body;
try {
const postbuf = await collection.findOne(
{
_id: new ObjectId(id),
"comments.idx": parseInt(idx)
},
{
projection: {
_id: 0,
"comments.$": 1
}
}
);
const comment = postbuf.comments.find(comment => comment.idx === parseInt(idx));
const commentPassword = comment.password
const match = await crypto.comparePasswords(password, commentPassword)
if (!match) { return res.status(404) }
const post = await collection.findOne(
{
_id: new ObjectId(id),
comments: { $elemMatch: { idx: parseInt(idx), password: commentPassword } },
},
);
if (!post) { return res.json({ isSuccess: false }); }
post.comments = post.comments.filter((comment) => comment.idx != parseInt(idx));
postService.updatePost(collection, id, post);
return res.json({ isSuccess: true });
} catch (error) {
console.log(error);
res.json({ isSuccess: false });
}
});