대딩코딩/웹개발 스터디
[Express] 15. Delete Comment POST
시데브
2023. 12. 1. 21:03
Post 방식으로 Delete Comment
파일명: commentRouter.js
const express = require('express');
const router = express.Router();
const commentController = require('../controllers/commentController.js');
router.post('/create/:topic_id', commentController.createComment);
router.post('/delete/:comment_id', commentController.deleteComment); //댓글 삭제
module.exports = router;
파일명: commentController.js
const commentModel = require('../models/commentModel.js');
module.exports = {
createComment: async (req, res) => {
const topicId = req.params.topic_id;
const newCommentData = req.body;
await commentModel.createComment(topicId, newCommentData);
res.redirect(`/topic/read/${topicId}`);
},
deleteComment: async (req, res) => {
const commentId = req.params.comment_id;
const comment = await commentModel.getComment(commentId); //댓글 가져오기
await commentModel.deleteComment(commentId); //댓글 삭제
res.redirect(`/topic/read/${comment.topic_id}`);
}
}
파일명: commentModel.js
const db = require('../config/db.js');
module.exports = {
createComment: async (topicId, newCommentData) => {
const query = 'INSERT INTO Comments(username, content, topic_id) VALUES(?, ?, ?);';
await db.query(query, [newCommentData.username, newCommentData.content, topicId]);
},
getComments: async (topicId) => {
const query = 'SELECT * FROM Comments WHERE topic_id=?;';
const comments = await db.query(query, [topicId]);
return comments[0];
},
deleteComment: async (commentId) => {
const query = 'DELETE FROM Comments WHERE comment_id=?;';
await db.query(query, [commentId]);
},
getComment: async (commentId) => {
const query = 'SELECT * FROM Comments WHERE comment_id=?;';
const comment = await db.query(query, [commentId]);
return comment[0][0];
}
}
>> 정상적으로 삭제됨
728x90
반응형