EditRestaurant

김종민·2022년 6월 29일
0

Nuber-Server

목록 보기
18/34


식당 주인이 Restaurant를 수정할 수 있게 하는 resolver

1. dtos/edit-restaurant.dto.ts

import { Field, InputType, ObjectType, PartialType } from '@nestjs/graphql';
import { MutationOutput } from 'src/common/dtos/output.dto';
import { CreateRestaurantInput } from './create-restaurant.dto';

@InputType()
export class EditRestaurantInput extends PartialType(CreateRestaurantInput) {
  @Field(() => Number)
  id: number;
}
///CreateRestaurantInput를 다 extends해서 PartialType으로 고르고 싶은 것만
///Choice할 수 있게 함.
///추가로 edit할 식당의 id를 입력해야하게 해 놓음.

@ObjectType()
export class EditRestaurantOutput extends MutationOutput {}

2. restaurant.resolver.ts

  @Mutation(() => EditRestaurantOutput)
  @Role(['Owner'])
  async editRestaurant(
    @AuthUser() owner: User,  ///loggedInUser를 owner로 받음.
    @Args('input') editRestaurantInput: EditRestaurantInput,
  ): Promise<EditRestaurantOutput> {
    return this.restaurantService.editRestaurant(owner, editRestaurantInput);
  }
  ///input에 owner와 editRestaurantInput를 넣어줌.

3. restaurant.service.ts

    async editRestaurant(
    owner: User,
    { id, categoryName, name, address, coverImg }: EditRestaurantInput,
  ): Promise<EditRestaurantOutput> {
  ///input될 owner와 id,....등등을 받아옴,
  
    try {
      const restaurant = await this.restaurants.findOneBy({ id });
      ///먼저, EditRestaurantInput의 id로 edit할 restaurant를 찾음.
      
      if (!restaurant) {
        return {
          ok: false,
          error: 'Restaurant not found',
        };
      }
      ///restaurant를 못찾으면, ok:false를 보냄.
      
      if (owner.id !== restaurant.ownerId) {
        return {
          ok: false,
          error: 'You can not edit Restaurant',
        };
      }
      ///AuthUser인 owner.id와 restaurant.ownerId가 다르면, ok:false.날림
      
      let category: Category = null;
      ///let으로 category를 만들고, 기본값으로 null을 넣어줌.
      
      if (categoryName) {
        category = await this.getOrCreateCategory(categoryName);
      }
      ///categoryName을 입력받았으면, getOrCreateCategory함수를 이용해서
      ///category를 만듬.
      
      await this.restaurants.save([
        {
          id: id,
          ...(category && { category }),
          name: name,
          address: address,
          coverImg: coverImg,
        },
      ]);
      ///위에서 id로 찾은 restaurant를 repository인 restaurants에 save함.
      ///...(category && { category })는 category가 있으면, 그기다 넣고,
      ///없으면, 그대로 사용한다는 의미임..
      
      return {
        ok: true,
      };
      ///여기까지 순조롭게 왔으면, true를 return함.
      
    } catch {
      return {
        ok: false,
        error: 'Could not edit Restaurant',
      };
    }
  }

이 부분도 만만치 않은 부분이라 마르고 닳도록 복습할것!!!!!

profile
코딩하는초딩쌤

0개의 댓글