저장을 습관화

게시글 조회 API 작성 중 "404 존재하지 않는 게시글입니다." 만들려면 본문

공부/node.js

게시글 조회 API 작성 중 "404 존재하지 않는 게시글입니다." 만들려면

ctrs 2023. 6. 29. 21:20

메모

환경은 node.js + express + mysql + sequelize

 

대충 아래와 같이 작성하고 있고,

// 게시글 상세 조회
router.get('/:postId', async (req, res) => {
  const { postId } = req.params;

  try {
    const post = await Post.findOne({
      include: [
        {
          model: User,
          attributes: ['nickname'],
        },
      ],
      attributes: [
        'id',
        'userId',
        'title',
        'content',
        'likes',
        'createdAt',
        'updatedAt',
      ],
      where: { id: postId },
      order: [['createdAt', 'DESC']],
    });

    return res.status(200).json({ data: post });
  } catch (error) {
    return res
      .status(400)
      .json({ errorMessage: '게시글 조회에 실패하였습니다.' });
  }
});

 

게시글의 'id'는 migration 폴더에서 자동으로 생성되고, 자동으로 증가된다고 설정해뒀음

id: {
        allowNull: false,
        autoIncrement: true,
        primaryKey: true,
        type: Sequelize.INTEGER,
      },

 

이에 따라 게시글을 작성하면

'id'는 뭐, 'userId'는 뭐, 'title'은 뭐... 이렇게 나올 것이고

 

작성한 게시글을 조회하기 위해

localhost:3000/api/posts/1 GET 요청을 보낸다면 잘 나옴

 

이때 파라피터로 존재하지 않는 게시글의 id를 입력한다면

{ "data": null } 이 나오는데 이를 status 404, 메세지는 "존재하지 않는 게시글입니다." 정도로 처리하고 싶음

 

- 해결

변수 선언 post 바로 아래에 !post 조건문만 추가해줬음

// 게시글 상세 조회
router.get('/:postId', async (req, res) => {
  const { postId } = req.params;

  try {
    const post = await Post.findOne({
      include: [
        {
          model: User,
          attributes: ['nickname'],
        },
      ],
      attributes: [
        'id',
        'userId',
        'title',
        'content',
        'likes',
        'createdAt',
        'updatedAt',
      ],
      where: { id: postId },
      order: [['createdAt', 'DESC']],
    });

    if (!post) {
      return res
        .status(404)
        .json({ errorMessage: '존재하지 않는 게시글입니다.' });
    }

    return res.status(200).json({ data: post });
  } catch (error) {
    return res
      .status(400)
      .json({ errorMessage: '게시글 조회에 실패하였습니다.' });
  }
});

난 또 response의 내용이 null이럴 때, 이런 식으로 되게 어렵게 생각했었는데 생각보다 별거 아니었음..

 

아니 다시 해보니까 조건문 처리를 post===null로 해줘도 되네

...
if (post === null) {
      return res
        .status(404)
        .json({ errorMessage: '존재하지 않는 게시글입니다.' });
    }
...