즐겨찾기 지역에 대한 알림을 보내는 API

tpids·2024년 7월 26일
0

project

목록 보기
14/26

notify.js

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

function formatDateToMySQL(date) {
    const d = new Date(date);
    return d.toISOString().slice(0, 19).replace('T', ' ');
}

/**
 * @swagger
 * /notify:
 *   post:
 *     tags:
 *       - favorites
 *     summary: Send a notification for a user's favorite zone
 *     description: Sends a notification to the user for their favorite surfing or diving zone. Updates the last_notified field if the notification is sent.
 *     requestBody:
 *       required: true
 *       content:
 *         application/json:
 *           schema:
 *             type: object
 *             properties:
 *               username:
 *                 type: string
 *                 description: The username of the user to send the notification to.
 *               surfing_zone_id:
 *                 type: integer
 *                 description: The ID of the surfing zone for which the notification is to be sent.
 *               diving_zone_id:
 *                 type: integer
 *                 description: The ID of the diving zone for which the notification is to be sent.
 *               notify_method:
 *                 type: string
 *                 enum: [email, sms]
 *                 description: The method of notification. Can be `email` or `sms`.
 *     responses:
 *       200:
 *         description: Notification status
 *         content:
 *           application/json:
 *             schema:
 *               type: object
 *               properties:
 *                 message:
 *                   type: string
 *                   example: 'Notification sent'
 *       404:
 *         description: Favorite not found
 *         content:
 *           application/json:
 *             schema:
 *               type: object
 *               properties:
 *                 error:
 *                   type: string
 *                   example: 'Favorite not found'
 *       500:
 *         description: Internal server error
 *         content:
 *           application/json:
 *             schema:
 *               type: object
 *               properties:
 *                 error:
 *                   type: string
 *                   example: 'Internal server error message'
 */
router.post('/', async (req, res) => {
    const { username, surfing_zone_id, diving_zone_id, notify_method } = req.body;

    if (!username || (!surfing_zone_id && !diving_zone_id) || !notify_method) {
        return res.status(400).json({ error: 'Missing required fields' });
    }

    try {
        let query = 'SELECT * FROM Favorite WHERE username = ? AND (';
        let queryParams = [username];

        if (surfing_zone_id) {
            query += 'surfing_zone_id = ?';
            queryParams.push(surfing_zone_id);
        }

        if (diving_zone_id) {
            if (surfing_zone_id) {
                query += ' OR ';
            }
            query += 'diving_zone_id = ?';
            queryParams.push(diving_zone_id);
        }

        query += ')';

        const [favorites] = await db.query(query, queryParams);

        if (favorites.length === 0) {
            return res.status(404).json({ error: 'Favorite not found' });
        }

        const favorite = favorites[0];
        const now = new Date();
        const lastNotified = favorite.last_notified ? new Date(favorite.last_notified) : null;
        const timeSinceLastNotified = lastNotified ? now - lastNotified : Infinity;

        if (timeSinceLastNotified > 24 * 60 * 60 * 1000) {

            const [updateResult] = await db.query('UPDATE Favorite SET last_notified = ? WHERE id = ?', [formatDateToMySQL(now), favorite.id]);

            if (updateResult.affectedRows === 0) {
                return res.status(500).json({ error: 'Failed to update last_notified' });
            }

            res.status(200).json({ message: 'Notification sent' });
        } else {
            res.status(200).json({ message: 'Notification not required' });
        }
    } catch (err) {
        console.error('Error during notification request:', err);
        res.status(500).json({ error: err.message });
    }
});

module.exports = router;
  • 요청 데이터 검증: 요청 본문에서 username, surfing_zone_id, diving_zone_id, notify_method가 모두 제공되었는지 확인합니다.
  • 쿼리 생성: 사용자가 설정한 surfing_zone_id 또는 diving_zone_id에 대해 쿼리를 동적으로 생성합니다.
  • 데이터베이스 쿼리: 즐겨찾기 목록을 조회하여 사용자의 즐겨찾기가 존재하는지 확인합니다.
  • 알림 시간 확인: 마지막 알림이 전송된 시간이 24시간 이상인지 확인합니다.
  • 업데이트 및 응답: 알림을 전송하고 last_notified 필드를 업데이트하며 성공 또는 실패 메시지를 응답으로 보냅니다.

이 코드는 사용자가 설정한 즐겨찾기 지역에 대해 알림을 보내고, 알림 전송 시 last_notified 필드를 업데이트하여 알림 전송 여부를 관리합니다.

profile
개발자

0개의 댓글