댓글 기능 API

tpids·2024년 7월 26일
0

project

목록 보기
19/26

댓글 기능 api

comment.js

const express = require('express');
const db = require('../config/dbConfig');
const router = express.Router();
const validateCommentInput = require('../middlewares/validateCommentInput'); 

// Create a new comment
/**
 * @swagger
 * /community/comments:
 *   post:
 *     summary: Create a new comment
 *     requestBody:
 *       required: true
 *       content:
 *         application/json:
 *           schema:
 *             type: object
 *             properties:
 *               post_id:
 *                 type: integer
 *               username:
 *                 type: string
 *               content:
 *                 type: string
 *     responses:
 *       201:
 *         description: The created comment
 *         content:
 *           application/json:
 *             schema:
 *               type: object
 *               properties:
 *                 comment_id:
 *                   type: integer
 *       400:
 *         description: Bad Request - Invalid input
 *       500:
 *         description: Internal server error
 */
router.post('/comments', validateCommentInput, async (req, res) => {
    const { post_id, username, content } = req.body;
    try {
        const [result] = await db.query(
            'INSERT INTO Comments (post_id, username, content) VALUES (?, ?, ?)',
            [post_id, username, content]
        );
        res.status(201).json({ comment_id: result.insertId });
    } catch (err) {
        console.error('Error during POST request:', err);
        res.status(500).json({ error: err.message });
    }
});

// Get all comments for a specific post
/**
 * @swagger
 * /community/comments/{post_id}:
 *   get:
 *     summary: Retrieve comments for a specific post
 *     parameters:
 *       - in: path
 *         name: post_id
 *         required: true
 *         schema:
 *           type: integer
 *         description: The post ID
 *     responses:
 *       200:
 *         description: A list of comments for the post
 *         content:
 *           application/json:
 *             schema:
 *               type: array
 *               items:
 *                 type: object
 *                 properties:
 *                   comment_id:
 *                     type: integer
 *                   post_id:
 *                     type: integer
 *                   username:
 *                     type: string
 *                   content:
 *                     type: string
 *                   created_at:
 *                     type: string
 *                     format: date-time
 *       404:
 *         description: Post not found
 */
router.get('/comments/:post_id', async (req, res) => {
    const { post_id } = req.params;
    try {
        const [rows] = await db.query('SELECT * FROM Comments WHERE post_id = ?', [post_id]);
        if (rows.length === 0) {
            return res.status(404).json({ error: 'Comments not found for this post' });
        }
        res.json(rows);
    } catch (err) {
        console.error('Error during GET request:', err);
        res.status(500).json({ error: err.message });
    }
});

module.exports = router;

community.js


...

const commentRouter = require('./comment'); // 추가

...

router.use('/comment', commentRouter); // 추가

app.js

...

const commentRouter = require('./routes/comment');  // 추가

...

app.use('/community', commentRouter);  // comment 추가

Swaggre UI 를 이용하여 테스트

댓글 작성

댓글 목록 조회

미들웨어 폴더에 있는
validateCommentInput.js

function validateCommentInput(req, res, next) {
    const { post_id, username, content } = req.body;
    if (!post_id || !username || !content) {
        return res.status(400).json({ error: 'Post ID, username, and content are required' });
    }
    next();
}

module.exports = validateCommentInput;
  • 데이터 입력 검증 : 댓글 작성에 필요한 모든 필드가 제공되었는지 확인

DB에 Comments 테이블 생성

CREATE TABLE Comments (
    comment_id INT AUTO_INCREMENT PRIMARY KEY,
    post_id INT,
    username VARCHAR(50),
    content TEXT,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    FOREIGN KEY (post_id) REFERENCES Community_Post(post_id),
    FOREIGN KEY (username) REFERENCES User(username)
);

Comments 테이블 데이터 확인

profile
개발자

0개의 댓글