혼자 고민해보기_ 개발/TIL (Today I Learned)

20230711(화)_ 노드 JS 심화 과제 보충

nuri-story 2023. 7. 11. 22:03

금일 달성 항목

1)  노드 JS 심화 Lv5 과제 보충 및 동료 도와주기

2) 타입스크립트 강의 듣기 50%


문제 해결 과정 1 - 댓글 목록 조회 Layered Architecture Pattern

[문제]

댓글 목록 조회에 Layered Architecture Pattern를 적용하려고 하는데 

// 댓글 목록 조회 API
router.get("/posts/:postId/comments", authMiddleware, async (req, res) => {
  try {
    const postId = req.params.postId; // DB에 저장된 postId를 불러옴

    // Comments에 있는 객체안 postId가 일치하는것을 찾으면 comments 변수에 담는다
    const comments = await Comments.findAll({
      where: { postId: postId },
    });

    // data변수에 위의 comments변수에 담긴 일치하는 postId를 map을 이용해 각 코멘트 하나씩 돌며 객체안을 반환
    const data = comments.map((comments) => {
      return {
        commentId: comments.commentId,
        content: comments.content,
        UserId: comments.UserId,
        createdAt: comments.createdAt,
        updatedAt: comments.updatedAt,
      };
    });
    // postId가 없을 경우
    if (!postId) return res.status(404).json({ errorMessage: "게시글이 존재하지 않습니다." });
    // response에 data안에 담긴 객체를 메세지로 반환
    res.status(200).json(data);
    // 에러 예외처리
  } catch (error) {
    return res.status(400).json({ errorMessage: "댓글 조회에 실패하였습니다." });
  }
});

 

 

아래와 같은 부분은 서비스에 있어야하는지?.. 레포지토리로 옮겨야하는지 헷갈렸습니다.

    // data변수에 위의 comments변수에 담긴 일치하는 postId를 map을 이용해 각 코멘트 하나씩 돌며 객체안을 반환
    const data = comments.map((comments) => {
      return {
        commentId: comments.commentId,
        content: comments.content,
        UserId: comments.UserId,
        createdAt: comments.createdAt,
        updatedAt: comments.updatedAt,
      };

 

[시도 및 해결]

튜터님께 여쭤보니 3가지의 구분이 어려우면

Controller는 서비스를 연결하기 위한 수단인 부분이고 

Repository 는 DB와 관련된 부분만 수행한다고 생각하고 

그 외 모두를 서비스에서 진행된다고 생각하면 편하다고 하셨습니다.

 

그래서 아래와 같은 코드는 서비스에 두는게 맞다고 하십니다.

    // data변수에 위의 comments변수에 담긴 일치하는 postId를 map을 이용해 각 코멘트 하나씩 돌며 객체안을 반환
    const data = comments.map((comments) => {
      return {
        commentId: comments.commentId,
        content: comments.content,
        UserId: comments.UserId,
        createdAt: comments.createdAt,
        updatedAt: comments.updatedAt,
      };

 

[알게된 점]

Layered Architecture Pattern은 회사나 사람 개개인에 따라 구분하는 기준이 조금씩 다를 수 있다고 하십니다.

상황에 맞게 적절히 사용하면되는 기법이라 생각했습니다.