티스토리 뷰

메인 화면에서 모임을 클릭하면 해당 모임에 대한 디테일 페이지를 모달창으로 띄울 예정이다.

 

* 모임별 디테일 페이지 URI : /clubs/:id (GET)

 

1. controllers/userController.js

const express = require("express");
const checkAuth = require("../middlewares/checkAuth");
const router = express.Router()

const clubService = require("../services/clubService")

// 모임별 디테일 페이지
router.get("/:id", checkAuth, async (req, res) => {
    const clubId = req.params.id
    const userId = req.user.id
    
    const getClubsById = await clubService.getClubsById(clubId)
    const getJoinInfoById = await clubService.getJoinInfoById({ clubId, userId })
    const countJoinedUsers = await clubService.getCountJoinedUsersById(clubId)
    
    return res.json({ getClubsById, getJoinInfoById, countJoinedUsers });
})
  • 조회하는 API기 때문에 HTTP Method는 GET을 이용했다.
  • 구현해뒀던 checkAuth 미들웨어를 통해 request를 한 유저 id 값을 받아온다.
  • getClubsById : 아이디별로 클럽 테이블 불러온다.
    getJoinInfoById : 해당 유저의 가입 정보를 불러온다.
    countJoinedUsers : 해당 클럽에 참여한 인원 수를 불러온다.

 

2. services/clubService.js

const db = require("../libs/db")

const CLUBS_WITH_CATEGORIES =
    `SELECT cb.id AS clubs_id, cb.name AS clubs_name, location, capacity, img, views, description,
    cg.id AS categories_id, cg.name AS categories_name
    FROM clubs AS cb LEFT JOIN categories AS cg ON cb.category_id = cg.id`
const JOIN_INFO_WITH_USERS =
    `SELECT users.id, users.name, status FROM clubs_users
    LEFT JOIN users ON clubs_users.user_id = users.id`

const clubService = {

    (...)
    
    getClubsById: async (clubId) => {
        const conn = await db.getConnection();
        
        const [clubsById] = await conn.query(`${CLUBS_WITH_CATEGORIES} WHERE cb.id = ?`, [clubId]);
        
        conn.release();
        
        return clubsById[0];
    },
    getJoinInfoById: async ({ clubId, userId }) => {
        const conn = await db.getConnection();
        
        const [joinInfoByClubId] = await conn.query(
            `${JOIN_INFO_WITH_USERS}
            WHERE club_id = ?`, [clubId]);
        const [joinInfoByClubAndUserIds] = await conn.query(
            `${JOIN_INFO_WITH_USERS}
            WHERE club_id = ? AND user_id = ?`, [clubId, userId]);
            
        conn.release();
        
        return { joinInfoByClubId, joinInfoByClubAndUserIds };
    },
    getCountJoinedUsersById: async (clubId) => {
        const conn = await db.getConnection();
        
        const [countJoinedUsers] = await conn.query(
            `SELECT COUNT(*) AS count FROM clubs_users
            WHERE status = "JOINED" AND club_id = ?`, [clubId]);
        
        conn.release();
        
        return countJoinedUsers[0].count;
    },
}

module.exports = clubService;
  • 여러 번 사용될 SQL문은 변수에 담았다.

 

getClubsById

getClubsById: async (clubId) => {
    const conn = await db.getConnection();

    const [clubsById] = await conn.query(`${CLUBS_WITH_CATEGORIES} WHERE cb.id = ?`, [clubId]);

    conn.release();

    return clubsById[0];
},
  • clubs 테이블과 categories 테이블을 join 해서 해당 클럽의 정보를 담아 반환한다.

 

getJoinInfoById

getJoinInfoById: async ({ clubId, userId }) => {
    const conn = await db.getConnection();

    const [joinInfoByClubId] = await conn.query(
        `${JOIN_INFO_WITH_USERS}
        WHERE club_id = ?`, [clubId]);
    const [joinInfoByClubAndUserIds] = await conn.query(
        `${JOIN_INFO_WITH_USERS}
        WHERE club_id = ? AND user_id = ?`, [clubId, userId]);

    conn.release();

    return { joinInfoByClubId, joinInfoByClubAndUserIds };
},
  • joinInfoByClubId : 해당클럽에 가입된 모든 유저 (가입 목록 표시할 때 필요)
    joinInfoByClubAndUserIds : 해당 클럽에 대한 유저의 가입상태를 알기 위해 필요

 

getCountJoinedUsersById

getCountJoinedUsersById: async (clubId) => {
    const conn = await db.getConnection();

    const [countJoinedUsers] = await conn.query(
        `SELECT COUNT(*) AS count FROM clubs_users
        WHERE status = "JOINED" AND club_id = ?`, [clubId]);

    conn.release();

    return countJoinedUsers[0].count;
},
  • 해당 클럽에 "가입 완료(JOINED)"된 유저의 수만 count.
    (가입 인원 표시하기 위해 필요)

 


 

  • JoinInfoByClubId와 JoinInfoByClubAndUserIds는 쿼리를 2번 날리기 보다
    JoinInfoByClubId만 받아오고, 거기서 UserId에 해당하는 것만 반환해주는 것이 좋을 것 같다.
    (백, 프론트 어디서 처리하든!)
  • 클럽에 참가한 인원은 프론트에서 이미 받아온 전체 모임 데이터를 가공해서 쓸 수 있을까?
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
TAG
more
«   2025/05   »
1 2 3
4 5 6 7 8 9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25 26 27 28 29 30 31
글 보관함