본문 바로가기
공부/express

[Express] API 작성법 (라우터, 컨트롤러 분리)

by 웅대 2024. 5. 16.
728x90
반응형

https://growth-coder.tistory.com/274

 

[express] express 웹 서버 기초

pacakage.json 생성npm init 명령어로 package.json을 만들어준다. package.json에는 프로젝트가 사용 중인 패키지의 정보가 담겨있다.package.json 문서를 통해 패키지를 쉽게 관리할 수 있다. npm init npm init 명

growth-coder.tistory.com

 

이전 포스팅에서 간단하게 express 사용법을 알아보면서 라우팅 기능도 알아보았다.

 

이 땐 서버 실행의 메인이 되는 index.js 파일에서 직접 API를 작성하였는데 이러한 방식은 프로젝트의 규모가 커질수록 index.js의 길이가 늘어나고 가독성이 떨어지는 단점이 있다.

 

이번 포스팅에서는 라우터와 컨트롤러를 분리해서 index.js의 코드를 줄이고 가독성을 높여보려고 한다.

 

기존 코드

user가 있고 각각의 user가 속해있는 team이 있고 이에 관한 CRUD api를 작성한다고 해보자.

 

<index.js>

const express = require('express')
app = express()

// 다
// 양
// 한

// 미
// 들
// 웨
// 어
app.listen(3001, ()=>{
    console.log("3001번 포트에서 서버 실행")
})

app.get('/teams', (req, res)=>{
    // 굉
    // 장
    // 히

    // 긴

    // 코
    // 드
    res.send(req.path)
})
app.post('/teams', (req, res)=>{
    // 굉
    // 장
    // 히

    // 긴

    // 코
    // 드
    res.send(req.path)
})
app.patch('/teams', (req, res)=>{
    // 굉
    // 장
    // 히

    // 긴

    // 코
    // 드
    res.send(req.path)
})
app.delete('/teams', (req, res)=>{
    // 굉
    // 장
    // 히

    // 긴

    // 코
    // 드
    res.send(req.path)
})
app.get('/users', (req, res)=>{
    // 굉
    // 장
    // 히

    // 긴

    // 코
    // 드
    res.send(req.path)
})
app.post('/users', (req, res)=>{
    // 굉
    // 장
    // 히

    // 긴

    // 코
    // 드
    res.send(req.path)
})
app.patch('/users', (req, res)=>{
    // 굉
    // 장
    // 히

    // 긴

    // 코
    // 드
    res.send(req.path)
})
app.delete('/users', (req, res)=>{
    // 굉
    // 장
    // 히

    // 긴

    // 코
    // 드
    res.send(req.path)
})

 

지금은 간단하게 표현했지만 실제로 모든 api를 index.js에서 작성하게 된다면 훨씬 복잡할 것이다.

라우터 분리

먼저 라우터를 분리해보자.

 

우리는 현재 user와 team에 관한 api를 작성했기 때문에 user와 team을 기준으로 라우터를 분리해보자.

 

</routes/team.js>

const express = require('express')
const router = express.Router()
router.get('/', (req, res)=>{
    // 굉
    // 장
    // 히

    // 긴

    // 코
    // 드
    res.send(req.path)
})
router.post('/', (req, res)=>{
    // 굉
    // 장
    // 히

    // 긴

    // 코
    // 드
    res.send(req.path)
})
router.patch('/', (req, res)=>{
    // 굉
    // 장
    // 히

    // 긴

    // 코
    // 드
    res.send(req.path)
})
router.delete('/', (req, res)=>{
    // 굉
    // 장
    // 히

    // 긴

    // 코
    // 드
    res.send(req.path)
})

module.exports = router

 

</routes/user.js>

const express = require('express')
const router = express.Router()
router.get('/', (req, res)=>{
    // 굉
    // 장
    // 히

    // 긴

    // 코
    // 드
    res.send(req.path)
})
router.post('/', (req, res)=>{
    // 굉
    // 장
    // 히

    // 긴

    // 코
    // 드
    res.send(req.path)
})
router.patch('/', (req, res)=>{
    // 굉
    // 장
    // 히

    // 긴

    // 코
    // 드
    res.send(req.path)
})
router.delete('/', (req, res)=>{
    // 굉
    // 장
    // 히

    // 긴

    // 코
    // 드
    res.send(req.path)
})

module.exports = router

 

자세히보면 경로의 앞 부분에 users와 teams와 같은 prefix가 없는 모습을 볼 수 있다.

 

이 prefix는 index.js에서 이 router들을 가져와서 붙여줄 예정이다.

 

<index.js>

const express = require('express')
const teamRouter = require('./routes/team')
const userRouter = require('./routes/user')
app = express()

// 다
// 양
// 한

// 미
// 들
// 웨
// 어
app.use('/teams', teamRouter)
app.use('/users', userRouter)
app.listen(3001, ()=>{
    console.log("3001번 포트에서 서버 실행")
})

 

컨트롤러 분리

라우터를 분리하여 index.js의 코드의 가독성이 높아졌다.

 

그런데 만약 라우터의 각 경로마다 처리하는 로직이 굉장히 복잡하다면 이 또한 가독성이 좋지 않을 것이다.

 

이번에는 라우터에서 컨트롤러를 분리해보자.

 

이 또한 controllers 디렉토리 내부에서 user와 team으로 분리할 예정이다.

 

<controllers/team.js>

module.exports.getTeam = (req, res)=>{
    // 굉
    // 장
    // 히

    // 긴

    // 코
    // 드
    res.send(req.path)
}
module.exports.postTeam = (req, res)=>{
    // 굉
    // 장
    // 히

    // 긴

    // 코
    // 드
    res.send(req.path)
}
module.exports.patchTeam = (req, res)=>{
    // 굉
    // 장
    // 히

    // 긴

    // 코
    // 드
    res.send(req.path)
}
module.exports.deleteTeam = (req, res)=>{
    // 굉
    // 장
    // 히

    // 긴

    // 코
    // 드
    res.send(req.path)
}

 

<controllers/user.js>

module.exports.getUser = (req, res)=>{
    // 굉
    // 장
    // 히

    // 긴

    // 코
    // 드
    res.send(req.path)
}
module.exports.postUser = (req, res)=>{
    // 굉
    // 장
    // 히

    // 긴

    // 코
    // 드
    res.send(req.path)
}
module.exports.patchUser = (req, res)=>{
    // 굉
    // 장
    // 히

    // 긴

    // 코
    // 드
    res.send(req.path)
}
module.exports.deleteUser = (req, res)=>{
    // 굉
    // 장
    // 히

    // 긴

    // 코
    // 드
    res.send(req.path)
}

 

이제 이 컨트롤러를 라우터에 연결해보자.

 

<routes/team.js>

const express = require('express')
const router = express.Router()
const controller = require('../controllers/team')
router.get('/', controller.getTeam)
router.post('/', controller.postTeam)
router.patch('/', controller.patchTeam)
router.delete('/', controller.deleteTeam)
module.exports = router

 

<routes/user.js>

const express = require('express')
const router = express.Router()
const controller = require('../controllers/user')
router.get('/', controller.getUser)
router.post('/', controller.postUser)
router.patch('/', controller.patchUser)
router.delete('/', controller.deleteUser)

module.exports = router


정리

  1. index.js에서 라우터 분리
  2. 라우터에서 컨트롤러 분리

 

728x90
반응형

댓글