더북(TheBook)

라우트를 추가한 다음에는 핸들러를 작성합니다.

api/comment/controllers/comment.js

const { sanitizeEntity } = require('strapi-utils');

module.exports = {
  async create(ctx) {
    (...)
  },
  async find(ctx) {
    (...)
  },
  async update(ctx) {
    const { articleId, id } = ctx.params; // URL 파라미터 추출
    // 댓글 조회
    const comment = await strapi.services.comment.findOne({
      id,
      article: articleId,
    });
    // 데이터가 존재하지 않을 때
    if (!comment) {
      return ctx.throw(404);
    }
    // article 또는 user 변경 막기
    if (ctx.request.body.article || ctx.request.body.user) {
      return ctx.throw(400, 'article or user field cannot be changed');
    }
    // 사용자 확인
    if (ctx.state.user.id !== comment.user.id) {
      return ctx.unauthorized(`You can't update this entry`);
    }
    // comment 데이터 업데이트
    const entity = await strapi.services.comment.update(
      {
        id,
      },
      ctx.request.body
    );
    // 응답 반환
    return sanitizeEntity(entity, { model: strapi.models.comment });
  },
};

댓글을 업데이트하는 로직은 게시글을 업데이트하는 로직과 비슷합니다. articleId와 댓글의 id를 사용하여 수정하려는 댓글이 존재하는지 확인하고, 해당 데이터가 존재한다면 update API를 사용하여 데이터를 변경합니다.