14.5.2 게시글 수정하기

    게시글을 수정하는 update 핸들러 함수를 작성합시다.

    api/article/controllers/article.js

    const { sanitizeEntity } = require('strapi-utils');
    
    module.exports = {
      async create(ctx) {
        (...)
      },
    
      async update(ctx) {
        const { id } = ctx.params; // URL 파라미터에서 id 추출
        const article = await strapi.services.article.findOne({ id }); // id로 데이터 조회
    
        // 데이터가 존재하지 않을 때
        if (!article) {
          return ctx.throw(404);
        }
    
        // user 정보는 변경할 수 없도록 처리
        if (ctx.request.body.user) {
          return ctx.throw(400, 'user field cannot be changed');
        }
    
        // 사용자의 id article의 작성자 id가 일치하는지 확인
        if (ctx.state.user.id !== article.user.id) {
          return ctx.unauthorized(`You can't update this entry`);
        }
        // article 데이터 업데이트
        const entity = await strapi.services.article.update(
          { id },
          ctx.request.body
        );
    
        // 응답 반환
        return sanitizeEntity(entity, { model: strapi.models.article });
      },
    };
    신간 소식 구독하기
    뉴스레터에 가입하시고 이메일로 신간 소식을 받아 보세요.