글 조회수 기능 API

tpids·2024년 7월 24일
0

project

목록 보기
12/26

comunity DB에 views 컬럼추가

// mysql

ALTER TABLE Community_Post
ADD views INTEGER;

comunity.js 코드 수정

// comunity.js

...

// 글 작성 기능
router.post('/posts', upload.single('image'), validatePostInput, async (req, res) => {
    const { username, title, content, post_date, latitude, longitude } = req.body;
    const image = req.file ? req.file.filename : null;
    try {
        const [user] = await db.query('SELECT * FROM User WHERE username = ?', [username]);
        if (user.length === 0) {
            return res.status(400).json({ error: 'Username does not exist' });
        }

        const formattedDate = formatDateToMySQL(post_date);
        const [result] = await db.query(
            'INSERT INTO Community_Post (username, title, content, post_date, latitude, longitude, image, views) VALUES (?, ?, ?, ?, ?, ?, ?, ?)',
            [username, title, content, formattedDate, latitude, longitude, image, 0] 
        );
        res.status(201).json({ post_id: result.insertId, imageUrl: `/uploads/${image}` });
    } catch (err) {
        console.error('Error during POST request:', err);
        res.status(500).json({ error: err.message });
    }
});

...

// 글 조회 기능
router.get('/posts/:id', async (req, res) => {
    const { id } = req.params;
    try {
        await db.query('UPDATE Community_Post SET views = views + 1 WHERE post_id = ?', [id]);

        const [rows] = await db.query('SELECT * FROM Community_Post WHERE post_id = ?', [id]);
        if (rows.length === 0) {
            return res.status(404).json({ error: 'Post not found' });
        }
        res.json(rows[0]);
    } catch (err) {
        console.error('Error during GET request:', err);
        res.status(500).json({ error: err.message });
    }
});

...

Swagger UI 테스트

글 작성

글 조회

전체 글 목록

DB에서 views 데이터 확인

profile
개발자

0개의 댓글