관리 메뉴

아보카도 Blog

Node.js 입문 과제 제출, 문제 설명, 코드 리뷰 본문

Node.js

Node.js 입문 과제 제출, 문제 설명, 코드 리뷰

수수 아보카도 2022. 12. 16. 17:41

<과제 제출>

1. API

 

Node 입문 개인과제 API 김수정

A new tool for teams & individuals that blends everyday work apps into one.

pale-target-69e.notion.site

게시글 전체/특정 게시글 조회, 게시글 작성, 댓글 조회, 댓글 작성 구현 완료.

게시글과 댓글 수정과 삭제는 해내지 못했다.

AWS 배포 완료

2. 코드

 

GitHub - tnwjd3315/nodejs_beginner_assignment

Contribute to tnwjd3315/nodejs_beginner_assignment development by creating an account on GitHub.

github.com

3. 과제 배포 ip 주소

게시글 전체 조회: http://43.201.110.0:3000/api/posts

특정 게시물의 댓글 조회: http://43.201.110.0:3000/api/comments/639b4bf6acf2808dd874fcbb

 

<문제 설명>

 

1. 라우터와 스키마의 차이

라우터는 표지판같은 것. 앤드포인트가 각각의 표지판이다. 어디로 가라는 매핑 포인트.

스키마는 메모리에 데이터들을 쌓고 여기에서 소통하는 것이 아니라,

몽고디비 등의 db와 연결할 때 모델이 필요하다. 몽고db에서 가져온 값을 객체로 매핑해주는 것이다.

즉, 데이터가 현실화된것.

 

2. AWS EC2 배포

포워딩: 외부에서 어떤 트래픽이 들어오면, 어디로 가라고 지시한 것.

특정 포트의 입력은 특정 포트로 가라는 걸 지시해준 것.

데이터와 API 서버는 분리가 되어있어야 한다. by 몽고디비 아틀라스

 

3. param, query, body

param은 url path의 일부 (restful API)

queryhttps://www.naver.com/search?keyword=“blah”&start_time=“20221210”처럼 ?뒤에 오는 애들.

쿼리 스트링을 통해 조건을 걸 수 있다.

body는 put, post 등에서 쓰이며 서버에 변경되어야 하는 사항을 말한다.

header에 content type을 application/json으로 보내야 한다.

 

4. http method- get, post, put, delete

 

5. Restful API

 

6. 역할별로 directory structure를 분리했을 때 유지 보수가 쉽다.

convention에 맞춰서 작성해주기.

 

<코드리뷰>

 

1. app.use 미들웨어

 

2. postsId(x), postId(o) s떼어주기

const post = findOne

res.json{{jposts}} key와 value가 같을 때는 하나만 적어줘도 된다. json notation

 

3. user뿐만 아니라 userId가 필요하다.

 

4. 

app.use(express.json())

body parser역할. body에 json이 왔을 때 미들웨어로 쓸 수 있다.

json으로 들어온 애들을 유용하게 parsing하기 위해 쓰인다.

 

5. 앤트리포인트가 루트 쪽에 있어야 한다. 이번 프로젝트에서는 app.js에 있어야 한다.

app.get('/', (req, res) => {
  res.send('Hello World!');
});

 

6. 전부 찾기. ({}) 안에 다 비워져있으면 다 찾아달라는 말.

// localhost:3000/api/posts GET Method 전체 게시글 조회
router.get("/posts", async(req,res) => {
  const posts = await Posts.find({})
  res.json({posts})
})

// localhost:3000/api/posts GET Method 특정 게시글 조회
router.get("/posts/:postsId", async(req,res) => {
  const {postsId} = req.params
  const post = await Posts.find({postsId: Number(postsId)})
  res.json({post})
})

verb가 리턴 값의 이름에 붙는 것은 좋은 네이밍 컨벤션이 아니다. ex.getAllPosts

postsId를 Number로 타입변경해서 줘야한다. 모델에서 그렇게 하라고 나와있으니까.

 

7. if를 쓰는 베스트케이스: 필터링을 통해 불필요한 케이스를 줄인다.

if (이거 위반했어?) {

 return ...

}

if (이것도 위반했어?) {

 return ...

}

다 통과되면 실제 비지니스 로직 실행.

  try{
    if (!pw || !title.length) {
      return res.return(400).json({
        success:false,
        errorMessage:"잘못된 접근입니다."
      })
    }
    await Posts.updateOne({title: title},{content: content})
        res.json({success: true})
  } catch (err) {
    console.log("잘못된 접근입니다.")
  } 
})

 

8. createdAt은 받을 필요가 없음

// localhost:3000/api/posts POST Method
router.post("/posts", async(req,res) => {
  const {user, title, content, createdAt, password} = req.body
  const createdPosts = await Posts.create({user, title, content, createdAt, password})
  res.json({ "postslist": createdPosts})
})

postsId, commentsId를 발급해주는 건 서버다. 내가 임의로 설정해주는 것이 아님.

예를 들면 댓글 post에서 받아야할 건 password, name, content 뿐이다. postId, commentsId, createdAt은 받아오지 않고 서버에서 자동으로 생성된다. 단 댓글 수정할 땐 commentsId 받아야겠지.

 

코드리뷰도 좋지만, 튜터님이 직접 코드를 어떻게 짜는지가 궁금했는데,

영훈 튜터님이 해설 강의 유투브에 올려주신다고 했으니까... 시간 남을 때 봐야겠다.