date/ 24.09.09.
/* 공부하며 정리한 내용이니 정확하지 않을 수 있습니다. 잘못된 내용은 댓글로 알려주세요!*/
저번에 로그인 페이지까지 간결하게 구현해 보았습니다. 오늘은 채널 API를 설계하고 페이지를 구현해 보겠습니다.
📌
자바스크립트에서 빈 객체를 확인하는 방법이 3가지 있습니다. 객체.keys()를 활용하는 방법, for문을 이용하여 안에 property가 있는지 하나하나 체크하는 방법, lodash라는 라이브러리를 활용하는 방법입니다. 그 중 가장 추천하는 방법은 객체.keys()를 활용하는 방법입니다.
const obj1 = {}
const obj2 = { message : "안 비었음" }
console.log(Object.keys(obj1))
console.log(Object.keys(obj2))
위의 코드를 실행해 보겠습니다.
메세지 하나 들어가 있는 배열을 반환합니다. 그럼 배열의 길이로 객체가 비었는지, 비지 않았는지 확인할 수 있겠네요!
const obj1 = {}
const obj2 = { message : "안 비었음" }
const num = 1
const str = "one"
console.log(Object.keys(obj1).length === 0) //length === 0
console.log(Object.keys(obj2).length === 0) //length === 1
console.log(Object.keys(num).length === 0)
console.log(Object.keys(str).length === 0)
위 코드를 실행시키면, 위에서 아래 순서대로 true, false, true, false가 로그에 찍힙니다. const num = 1의 길이가 0이라구요? 이거 정말 말도 안 되는군요. str은 제대로 작동하는데... 문자열에도 length가 0인지 확인하는 것이 먹히는지 보겠습니다.
const obj1 = {}
const obj2 = { message : "안 비었음"}
const num = 1
const str1 = "one"
const str2 = ""
console.log(Object.keys(obj1).length === 0) //length === 0
console.log(Object.keys(obj2).length === 0) //length === 1
console.log(Object.keys(num).length === 0)
console.log(Object.keys(str1).length === 0)
console.log(Object.keys(str2).length === 0)
위의 코드를 실행시켜 보겠습니다.
문자열에서도 length를 확인할 수 있습니다. 문자열도 자바스크립트에서는 결국 객체이기 때문에 가능한 일입니다. 그렇기에 아예 함수를 만들어서 모듈처럼 활용할 수 있습니다.
function isEmpty(obj) {
if (Object.keys(obj).length === 0) {
return true;
} else {
return false;
}
}
📌
그럼 이제 채널 API 설계를 진행해 보도록 하겠습니다.
1. 채널 생성: POST /channels
- req: body (channelTitle)
- res: status code 201, `${channelTitle}님 채널 운영을 응원합니다!`
2. 채널 수정: PUT /channels/:id
- req: URL(id), 수정할 내용(body - channelTitle)
- res: status code 200, `채널명이 {}에서 {}로 정상 수정되었습니다.`
3. 채널 삭제: DELETE /channels/:id
- req: URL(id)
- res: status code 200, `{} 채널이 성공적으로 삭제되었습니다.`
4. 채널 전체 조회: GET /channels
- req: X
- res: status code 200, 채널 전체 데이터 뿌려주기(list? or json array?)
5. 채널 개별 조회: GET /channels/:id
- req: URL(id)
- res: status code 200, 채널 개별 데이터
📌
좀 더 코드를 간결화하기 위해 route를 활용해 보겠습니다.
//express 모듈 세팅
const express = require('express')
const app = express()
app.use(express.json())
app.listen(9999)
//db 세팅
let db = new Map()
var id = 1
//route로 같은 url 묶어두기
//채널 개별 생성, 채널 전체 조회
app
.route('/channels')
.get((req, res) => {
res.send("전체 조회")
}) //전체 조회
.post((req, res) => {
res.send("개별 생성")
}) //개별 생성
//채널 개별 수정, 채널 개별 삭제, 개별 조회
app
.route('/channels/:id')
.put((req, res) => {
res.send("개별 수정")
}) //채널 개별 수정
.delete((req, res) => {
res.send("개별 삭제")
}) //개별 삭제
.get((req, res) => {
res.send("개별 조회")
}) //개별 조회
(처음엔 이걸 굳이 왜 하나... 싶었는데 훨씬 간결하고 동일한 내용 계속 타이핑하지 않아도 되니까 좋네요 ㅎ)
📌
//express 모듈 세팅
const express = require('express')
const app = express()
app.use(express.json())
app.listen(9999)
//db 세팅
let db = new Map()
var id = 1
//route로 같은 url 묶어두기
//채널 개별 생성, 채널 전체 조회
app
.route('/channels')
.get((req, res) => { //전체 조회
var channels = []
db.forEach((value, key) => {
channels.push(value)
})
if (db.size) {
res.status(200).json(channels)
} else {
res.status(404).json({
message : "등록된 채널이 존재하지 않습니다."
})
}
})
.post((req, res) => { //개별 생성
if (req.body.channelTitle) {
db.set(id++, req.body)
res.status(201).json({
messsage : `${db.get(id-1).channelTitle}님 채널 운영을 응원합니다!`
})
} else {
res.status(400).json({
message : "채널명이 입력되지 않았습니다."
})
}
})
//채널 개별 수정, 채널 개별 삭제, 개별 조회
app
.route('/channels/:id')
.put((req, res) => { //채널 개별 수정
let {id} = req.params
id = parseInt(id)
var channel = db.get(id)
var oldTitle = channel.channelTitle
if (channel) {
var newTitle = req.body.channelTitle
channel.channelTitle = newTitle
db.set(id, channel)
res.json({
message : `채널명이 ${oldTitle}에서 ${newTitle}로 정상 수정되었습니다.`
})
} else {
res.status(404).json({
message : "채널 정보를 찾을 수 없습니다."
})
}
})
.delete((req, res) => { //개별 삭제
let {id} = req.params
id = parseInt(id)
var channel = db.get(id)
if (channel) {
db.delete(id)
res.status(200).json({
message : `${channel.channelTitle} 채널이 성공적으로 삭제되었습니다.`
})
} else {
res.status(404).json({
message : "채널 정보를 찾을 수 없습니다."
})
}
})
.get((req, res) => { //개별 조회
let {id} = req.params
id = parseInt(id)
var channel = db.get(id)
if (channel) {
res.status(200).json(channel)
} else {
res.status(404).json({
message : "채널 정보를 찾을 수 없습니다."
})
}
})
'학습 기록 > 데브코스 웹 풀스택 4기' 카테고리의 다른 글
백엔드 심화: DB 기본 (0) | 2024.09.11 |
---|---|
백엔드 기초: 마무리, express (5) | 2024.09.10 |
백엔드 기초: 전체 조회, forEach와 map, delete (5) | 2024.09.05 |
백엔드 기초: postman과 post (1) | 2024.09.04 |
백엔드 기초: map object, 함수 (1) | 2024.09.03 |