티스토리 뷰

 

문제

comments(댓글) 도메인의 API가 제대로 동작하지 않음

해당 모델의 메서드를 찾을 수 없다는 에러가 발생

{
    "message": "Cannot read properties of undefined (reading 'findOne')"
}

 

시도 및 해결

원인

터미널의 ErrorMessage와 경로 등을 확인해보니 postRepository에서 최초 발생한 것을 확인함

PostRepository을 Jest로 테스트해보기 위해, 코드를 일부 바꿨는데

CommentRepository, CommetService에도 PostRepository를 사용하고 있어 생긴 문제

 

PostRepository : 생성자 인자가 필요함

// repositories/postRepository.js

const { Posts, Users, LikePosts, sequelize } = require("../models");
const { Op } = require("sequelize");

class PostRepository {
  constructor(PostsModel, UserModel, LikePostModel) { // 3개의 인자를 받아 생성됨
    this.postModel = PostsModel;
    this.userModel = UserModel;
    this.likePostModel = LikePostModel;
  }

// .. 중략 ..

module.exports = PostRepository;

CommentService

// controllers/postController.js

const PostRepository = require("../repositories/postRepository.js");
const UserRepository = require("../repositories/userRepository.js");
const CommentRepository = require("../repositories/commentRepository.js");

class CommentService {
  constructor() {
    this.postRepository = new PostRepository();
    this.userRepository = new UserRepository();
    this.commentRepository = new CommentRepository(); // 인자를 전달하지 않고 있음
  }

  // 게시글의 댓글 목록 조회
  getCommentList = async ({ postId }) => {
    // 게시글 존재 확인
    const existPost = await this.postRepository.findByPostId({ postId });
    if (!existPost) {
      return { errorMessage: "게시글 조회에 실패하였습니다." };
    }
    // 해당 게시글 댓글 전체 조회
    const comments = await this.commentRepository.findAllByPost({ postId });

// .. 중략 .. 

module.exports = CommentService;

 

 

해결

CommentService : 생성된 모든 레포지토리 다 의존성 주입해줌

const PostRepository = require("../repositories/postRepository.js");
const UserRepository = require("../repositories/userRepository.js");
const CommentRepository = require("../repositories/commentRepository.js");
const { Posts, Users, Comments, LikePosts } = require("../models");

class CommentService {
  constructor() {
    this.postRepository = new PostRepository(Posts, Users, LikePosts);
    this.userRepository = new UserRepository(Users);
    this.commentRepository = new CommentRepository(Comments);  // models/Comments.js 를 불러와 전달
  }
 // 게시글의 댓글 목록 조회
  getCommentList = async ({ postId }) => {
    // 게시글 존재 확인
    const existPost = await this.postRepository.findByPostId({ postId });
    if (!existPost) {
      return { errorMessage: "게시글 조회에 실패하였습니다." };
    }
    // 해당 게시글 댓글 전체 조회
    const comments = await this.commentRepository.findAllByPost({ postId });

// .. 중략 .. 

module.exports = CommentService;

 

CommentRepository : CommentService에서 인자를 받아 commentModel 주입

const { Comments } = require("../models");
const { Op } = require("sequelize");

class CommentRepository {
  constructor(CommentModel) {  // CommentService 에서 받은 Comments 모델을 활용
    this.commentModel = CommentModel;
  }
  // 댓글 생성
  create = async ({ content, postId, userId }) => {
    await this.commentModel.create({
      content,
      PostId: postId,
      UserId: userId,
    });
    return;
  };

// .. 중략 ..

module.exports = CommentRepository;

 

 

알게 된 점

각 도메인의 서비스와 레포지토리를 긴밀하게 연결되어 있어, 당연하게도 코드를 조금 바꾸더라도 나머지 모듈에 영향을 미침

 

댓글