웹 풀사이클 데브코스 TIL [Day 21] - express.Router()로 리팩토링

JaeKyung Hwang·2023년 12월 15일
0
post-thumbnail

2023.12.15(금)

🧭Node.js에서의 라우팅(Routing)?

Request(요청)이 왔을 때, 적절한 방향으로 경로를 안내해주는 것

  • Express에서는 express.Router() middleware를 사용하여 모듈화 가능
  • const router = express.Router()로 생성한 라우터 객체는 기존의 app 객체와 동일한 방식으로 사용 가능

📍어제 간단히 진행됐었던 미니 프로젝트의 ERD를 그려보고 이에 따라 API 설계 및 기존 demo 코드들을 수정했다.

🏗️미니 프로젝트 (유튜브) 수정

🎨ERD(Entity Relationship Diagram)

  • 구독자 수와 동영상 개수는 나중에 추가 (한번에 하면 api가 복잡해짐)

🖋️API 설계

  • 회원
    • 로그인 (POST /login : body(userId, pwd))
      • ${name}님 환영합니다. → 메인 페이지로 redirect
    • 회원 가입 (POST /join : body(userId, pwd, name))
      • ${name}님 환영합니다. → 로그인 페이지로 redirect
    • 마이페이지 = 회원 개별 조회 (GET /users : body(userId))
      (※ 원래 userId는 body가 아니라 header에 숨겨서 Token(JWT)으로 받아야함)
    • 마이페이지 > 회원 개별 탈퇴 (DELETE /users : body(userId))
      (※ 원래 userId는 body가 아니라 header에 숨겨서 Token(JWT)으로 받아야함)
      • ${name}님 다음에 또 뵙겠습니다. → 메인 페이지로 redirect
  • 마이페이지 > 채널 관리 (계정 하나로 최대 100개의 채널 관리 가능)
    • 회원의 채널 전체 조회 (GET /channels : body(userId))
    • 채널 개별 생성 (POST /channels : body(channelTitle, userId))
      (※ 원래 userId는 body가 아니라 header에 숨겨서 Token(JWT)으로 받아야함)
      • ${channelTitle} 채널을 응원합니다. → 채널 관리 페이지로 redirect
    • 채널 개별 수정 (PUT /channels/:id : channelTitle)
      • 채널명이 ${oldChannelTitle}에서 ${newChannelTitle}()로 성공적으로 수정되었습니다.
    • 채널 개별 삭제 (DELETE /channels/:id)
      • ${channelTitle} 채널이 삭제되었습니다 → 메인 페이지로 redirect
    • 채널 개별 조회 (GET /channels/:id)

💻CODE

  • 폴더 구조

    .
    │  app.js
    │  package-lock.json
    │  package.json
    │
    ├─node_modules
    │
    └─routes
            channels.js
            users.js
  • app.js

    const express = require('express')  // npm install express
    const app = express()
    const port = 8888
    app.listen(port, () => console.log(`> Server is running on http://localhost:${port}/`))
    
    const userRouter = require('./routes/users')
    const channelRouter = require('./routes/channels')
    
    app.use(express.json())
    app.use('/', userRouter)
    app.use('/channels', channelRouter)
  • routes/users.js

    const express = require('express')
    const router = express.Router()
    
    const db = new Map()
    
    // 로그인
    router.post('/login', (req, res) => {
        const { userId, pwd } = req.body
        if (userId && pwd) {
            if (db.has(userId)) {
                const user = db.get(userId)
                if (user.pwd == pwd) res.status(200).json({ message: `${user.name}님 환영합니다.` })
                else res.status(400).json({ message: "잘못된 비밀번호입니다." })
            } else {
                res.status(404).json({ message: "존재하지 않는 아이디입니다." })
            }
        } else {
            res.status(400).json({ message: "잘못된 형식입니다." })
        }
    })
    // 회원 가입
    router.post('/join', (req, res) => {
        const { userId, pwd, name } = req.body
        if (userId && pwd && name) {
            db.set(userId, req.body)
            res.status(201).json({ message: `${name}님 환영합니다.` })
        } else {
            res.status(400).json({ message: "잘못된 형식입니다." })
        }
    })
    
    router.route('/users')
        .get((req, res) => {    // 회원 개별 조회
            let { userId } = req.body
            if (db.has(userId)) {
                const user = db.get(userId)
                res.status(200).json({ userId: user.userId, name: user.name })
            } else {
                res.status(404).json({ message: "존재하지 않는 회원입니다." })
            }
        })
        .delete((req, res) => { // 회원 개별 탈퇴
            let { userId } = req.body
            if (db.has(userId)) {
                const { name } = db.get(userId)
                db.delete(userId)
                res.status(200).json({ message: `${name}님 다음에 또 뵙겠습니다.` })
            } else {
                res.status(404).json({ message: "존재하지 않는 회원입니다." })
            }
        })
    
    module.exports = router
  • routes/channels.js

    • 채널 개별 생성 시 존재하는 userId만 들어오는 것으로 간주 (지금은 간단히 Map을 db처럼 사용하고 있기 때문에 추후 실제 MariaDB와 연결할 때 이 부분 처리)
    const express = require('express')
    const router = express.Router()
    
    const db = new Map()
    var id = 0
    
    const channelNotFound = (res) => res.status(404).json({ message: "채널이 존재하지 않습니다." })
    
    router.route('/')
        .get((req, res) => {    // 채널 전체 조회
            const { userId } = req.body
            if (db.size && userId) {
                let channels = []
                db.forEach((value) => {
                    if (value.userId === userId)
                        channels.push(value)
                })
                if (channels.length) res.status(200).json(channels)
                else channelNotFound(res)
            } else {
                channelNotFound(res)
            }
        })
        .post((req, res) => {    // 채널 개별 생성
            if (req.body.channelTitle) {
                db.set(++id, req.body)
                res.status(201).json({ message: `${db.get(id).channelTitle} 채널을 응원합니다.` })
            } else {
                res.status(400).json({ message: "잘못된 형식입니다." })
            }
        })
    
    router.route('/:id')
        .get((req, res) => { // 채널 개별 조회
            let { id } = req.params
            id = parseInt(id)
            if (db.has(id)) res.status(200).json(db.get(id))
            else channelNotFound(res)
        })
        .put((req, res) => { // 채널 개별 수정
            let { id } = req.params
            id = parseInt(id)
            if (db.has(id)) {
                const channel = db.get(id)
                const oldChannelTitle = channel.channelTitle
                const newChannelTitle = req.body.channelTitle
                channel.channelTitle = newChannelTitle
                // db.set(id, channel)
                res.status(200).json({ message: `채널명이 ${oldChannelTitle}에서 ${newChannelTitle}(으)로 성공적으로 수정되었습니다.` })
            } else {
                channelNotFound(res)
            }
        })
        .delete((req, res) => {  // 채널 개별 삭제
            let { id } = req.params
            id = parseInt(id)
            if (db.has(id)) {
                const { channelTitle } = db.get(id)
                db.delete(id)
                res.status(200).json({ message: `${channelTitle} 채널이 삭제되었습니다` })
            } else {
                channelNotFound(res)
            }
        })
    
    module.exports = router

빨리 실제 DB와 연결해보고 싶다.

profile
이것저것 관심 많은 개발자👩‍💻

0개의 댓글