-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathcomment.html
321 lines (299 loc) · 9.63 KB
/
comment.html
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
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
<!-- 부트스트랩 받기 -->
<link
href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css"
rel="stylesheet"
integrity="sha384-4bw+/aepP/YC94hEpVNVgiZdgIC5+VKNBQNGCHeKRQN+PtmoHDEXuppvnDJzQIu9"
crossorigin="anonymous"
/>
<script
src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"
integrity="sha384-HwwvtgBNo3bZJJLYd8oVXjrBZt8cqVSpeBNS5n7C8IVInixGAoxmnlMuBnhbgrkm"
crossorigin="anonymous"
></script>
<!-- 제이쿼리 받기 -->
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/jquery.min.js"></script>
<link rel="stylesheet" type="text/css" href="./comment.css" />
<script type="module">
// firebase db 설정
const firebaseConfig = {
databaseURL:
"https://sparta-33d77-default-rtdb.asia-southeast1.firebasedatabase.app",
};
// DB에서 가장 최근에 등록된 댓글 가져와서 페이지에 댓글 추가하기
async function fetchLastCommentByRest() {
const username = $("#username").text() || "테스트유저";
const options = {
method: "GET",
headers: {
"Content-Type": "application/json",
},
};
const response = fetch(
firebaseConfig.databaseURL +
`/comments.json?orderBy="username"&equalTo="${username}"`,
options
).then((response) => {
response
.json()
.then((comments) => {
const commentEntries = Object.entries(comments);
// 댓글 빨리 단 순으로 정렬
commentEntries.sort((a, b) => {
const dateA = a[1].createdAt;
const dateB = b[1].createdAt;
return convertToDate(dateB) - convertToDate(dateA);
});
// 댓글 하나만 생성
const [key, value] = commentEntries[0];
createCommentDiv(key, value);
})
.catch((error) => {
console.error("fetch comment by rest: " + error);
});
});
}
// DB에서 댓글 전부 가져오고 페이지에도 등록함
async function fetchCommentsByRest() {
const username = $("#username").text() || "테스트유저";
const options = {
method: "GET",
headers: {
"Content-Type": "application/json",
},
};
const response = fetch(
firebaseConfig.databaseURL +
`/comments.json?orderBy="username"&equalTo="${username}"`,
options
).then((response) => {
response
.json()
.then((comments) => {
const commentEntries = Object.entries(comments);
// 댓글 빨리 단 순으로 정렬
commentEntries.sort((a, b) => {
const dateA = a[1].createdAt;
const dateB = b[1].createdAt;
return convertToDate(dateA) - convertToDate(dateB);
});
// 댓글 모두 생성
commentEntries.forEach(([key, value]) => {
createCommentDiv(key, value);
});
})
.catch((error) => {
console.error("fetch comment by rest: " + error);
});
});
}
// DB에 댓글 등록하고 페이지에도 등록함
async function submitCommentByRest() {
const commentAuthor = $("#comment-name").val();
const content = $("#comment-content").val();
const username = $("#username").text() || "테스트유저";
const createdAt = new Date().toLocaleString();
const data = {
username: username,
commentAuthor: commentAuthor,
content: content,
createdAt: createdAt,
};
const options = {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(data),
};
try {
await fetch(firebaseConfig.databaseURL + "/comments.json", options);
console.log("comment added by rest");
clearCommentForm();
await fetchLastCommentByRest();
} catch (error) {
console.error("comment add by rest" + error);
}
}
// DB에서 댓글 수정하고 댓글 리스트에서도 수정
async function updateCommentByRest() {
const commentKey = $(".click-update").data("functionArg");
const data = {
content: $("#comment-update-content").val(),
};
const options = {
method: "PATCH",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(data),
};
try {
await fetch(
firebaseConfig.databaseURL + `/comments/${commentKey}.json`,
options
);
console.log("update comment by rest!");
$(".click-update").find("p.fs-5").text(data.content);
clearClickedClass();
} catch (error) {
console.error("update comment by rest" + error);
}
}
// 수정하기 버튼 누르면 댓글 식별값 표시하고 수정 폼에 현재 댓글 내용 입력
function updateButtonClicked(commentKey) {
$(`[data-function-arg="${commentKey}"]`).addClass("click-update");
const comment = $(`[data-function-arg="${commentKey}"]`)
.find("p.fs-5")
.text();
$("#comment-update-content").val(comment);
$("#exampleModal").on("hidden.bs.modal", function (e) {
clearClickedClass();
});
}
// 수정 모달에서 취소 식별값 삭제
function clearClickedClass() {
$(".click-update").removeClass("click-update");
}
// DB에서 댓글 삭제하고 댓글 리스트에서도 삭제
async function deleteCommentByRest(commentKey) {
const options = {
method: "DELETE",
headers: {
"Content-Type": "application/json",
},
};
try {
await fetch(
firebaseConfig.databaseURL + `/comments/${commentKey}.json`,
options
);
console.log("delete comment by rest!");
clearComment(commentKey);
} catch (error) {
console.error("delete comment by rest " + error);
}
}
// 페이지에 댓글 하나 추가하기
function createCommentDiv(key, comment) {
const commentDivTemplate = `<div class="comment-wrapper" data-function-arg="${key}"><div class="row justify-content-between">
<div class="col-2"><p class="text-start fs-4">${comment.commentAuthor}</p></div>
<div class="col-2">
<p class="text-end">
<button type="button" data-bs-toggle="modal" data-bs-target="#exampleModal"
class="btn" onclick="updateButtonClicked('${key}')">수정</button>
<button type="button" class="btn" onclick="deleteComment('${key}')">삭제</button>
</p>
</div>
</div>
<div class="row">
<div class="col-12">
<p class="text-start fs-5">${comment.content}</p>
</div>
</div>
<div class="row">
<div class="col-3"><p class="text-start fs-6">${comment.createdAt}</p></div>
</div></div>`;
$(".comments").append(commentDivTemplate);
}
// 날짜 문자열을 Date 객체로 변환
function convertToDate(str) {
const [datePart, timePart] = str.split(" 오후 ");
const [year, month, day] = datePart.split(". ").map(Number);
const [hour, minute, second] = timePart.split(":").map(Number);
const convertedHour = hour === 12 ? hour : hour + 12;
const date = new Date(
Date.UTC(year, month - 1, day, convertedHour, minute, second)
);
return date;
}
// 댓글 리스트에서 댓글 삭제
function clearComment(commentKey) {
$(`[data-function-arg="${commentKey}"]`).remove();
}
// 댓글 폼 내용 삭제
function clearCommentForm() {
$("#comment-name").val("");
$("#comment-content").val("");
}
// 댓글 등록 버튼에 이벤트 등록
// module의 함수는 스코프가 script 태그라서 이렇게 해야함
$(".comment-submit-button").on("click", submitCommentByRest);
window.updateComment = updateCommentByRest;
window.deleteComment = deleteCommentByRest;
window.updateButtonClicked = updateButtonClicked;
window.clearClickedClass = clearClickedClass;
fetchCommentsByRest();
</script>
<!-- 댓글 등록 폼 -->
<div class="container text-center">
<div class="row comment-form">
<div class="col-2">
<input
class="form-control comment-name-input"
type="text"
placeholder="이름"
id="comment-name"
aria-label="default input example"
/>
</div>
<div class="col-8">
<textarea
class="form-control comment-content-input"
placeholder="내용을 입력해주세요!"
id="comment-content"
></textarea>
</div>
<div class="col-2">
<button type="button" class="btn btn-primary comment-submit-button">
등록
</button>
</div>
</div>
</div>
<div class="container text-center comments"></div>
<!-- 댓글 수정 모달, 속성 많은데 잘 몰라서 안건드리고 필요한 것만 조금 수정했음 -->
<div
class="modal fade"
id="exampleModal"
tabindex="-1"
aria-labelledby="exampleModalLabel"
aria-hidden="true"
>
<div class="modal-dialog modal-dialog-centered">
<div class="modal-content">
<div class="modal-header">
<h1 class="modal-title fs-5" id="exampleModalLabel">댓글 수정하기</h1>
<button
type="button"
class="btn-close"
data-bs-dismiss="modal"
aria-label="Close"
></button>
</div>
<div class="modal-body">
<textarea
class="form-control comment-content-input"
id="comment-update-content"
></textarea>
</div>
<div class="modal-footer">
<button
type="button"
class="btn btn-secondary"
onclick="clearClickedClass()"
data-bs-dismiss="modal"
>
취소
</button>
<button
type="button"
class="btn btn-primary"
data-bs-dismiss="modal"
onclick="updateComment()"
>
수정하기
</button>
</div>
</div>
</div>
</div>