Flare-k

[Add] comment

/* eslint-disable no-console */
import routes from "../routes";
import Video from "../models/Video";
import Comment from "../models/Comment";
// db를 import 해주고 home에 async를 달아준다. async는 기다려주는 역할을 한다.
// javascript가 db를 다 못보고 그냥 지나갈 수도 있기 때문이다.
......@@ -62,7 +63,9 @@ export const videoDetail = async (req, res) => {
params: { id },
} = req;
try {
const video = await Video.findById(id).populate("creator");
const video = await Video.findById(id)
.populate("creator")
.populate("comments");
res.render("videoDetail", { pageTitle: video.title, video });
} catch (error) {
res.redirect(routes.home);
......@@ -136,3 +139,25 @@ export const postRegisterView = async (req, res) => {
res.end();
}
};
// 댓글 부분
export const postAddComment = async (req, res) => {
const {
params: { id }, // URL에서 가져옴
body: { comment },
user,
} = req;
try {
const video = await Video.findById(id);
const newComment = await Comment.create({
text: comment,
creator: user.id,
});
video.comments.push(newComment.id);
video.save();
} catch (error) {
res.status(400);
} finally {
res.end();
}
};
......
import express from "express";
import routes from "../routes";
import { postRegisterView } from "../controllers/videoController";
import {
postRegisterView,
postAddComment,
} from "../controllers/videoController";
const apiRouter = express.Router();
apiRouter.post(routes.registerView, postRegisterView);
apiRouter.post(routes.addComment, postAddComment);
export default apiRouter;
......
......@@ -31,6 +31,9 @@ const FB_CALLBACK = "/auth/facebook/callback";
const API = "/api";
const REGISTER_VIEW = "/:id/view";
// Comment
const ADD_COMMENT = "/:id/comment";
const routes = {
home: HOME,
join: JOIN,
......@@ -78,6 +81,7 @@ const routes = {
api: API,
registerView: REGISTER_VIEW,
addComment: ADD_COMMENT,
};
// template에서 직접 접근이 필요한 경우 함수로 바꿔준다.
export default routes;
......
......@@ -23,4 +23,9 @@ block content
if video.comments.length === 1
span.video__comment-number 1 comment
else
span.video__comment-number #{video.comments.length} comments
\ No newline at end of file
span.video__comment-number #{video.comments.length} comments
form.add__comment#jsAddComment
input(type="text", placeholder="Add a comment", name="comment")
ul.video__comments-list
each comment in video.comments
span comment.text
\ No newline at end of file
......