2023.12.15(금)
Request(요청)이 왔을 때, 적절한 방향으로 경로를 안내해주는 것
express.Router()
middleware를 사용하여 모듈화 가능const router = express.Router()
로 생성한 라우터 객체는 기존의 app
객체와 동일한 방식으로 사용 가능📍어제 간단히 진행됐었던 미니 프로젝트의 ERD를 그려보고 이에 따라 API 설계 및 기존 demo 코드들을 수정했다.
POST /login
: body(userId, pwd))${name}님 환영합니다.
→ 메인 페이지로 redirectPOST /join
: body(userId, pwd, name))${name}님 환영합니다.
→ 로그인 페이지로 redirectGET /users
: body(userId))DELETE /users
: body(userId))${name}님 다음에 또 뵙겠습니다.
→ 메인 페이지로 redirectGET /channels
: body(userId))POST /channels
: body(channelTitle, userId))${channelTitle} 채널을 응원합니다.
→ 채널 관리 페이지로 redirectPUT /channels/:id
: channelTitle)채널명이 ${oldChannelTitle}에서 ${newChannelTitle}()로 성공적으로 수정되었습니다.
DELETE /channels/:id
)${channelTitle} 채널이 삭제되었습니다
→ 메인 페이지로 redirectGET /channels/:id
)폴더 구조
.
│ 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
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와 연결해보고 싶다.