createRestaurant

김종민·2022년 6월 29일
0

Nuber-Server

목록 보기
16/34

들어가기
restaurant를 만드는 mutaion.
category를 초이스하는게 아니라,
기존에 존재하면, 연결하고, 존재하지 않으면, 새로 만드는
과정을 주의깊게 알아본다.

1. dtos/create-restaurant.dto.ts

import { Field, InputType, ObjectType, PickType } from '@nestjs/graphql';
import { MutationOutput } from 'src/common/dtos/output.dto';
import { Restaurant } from '../entities/restaurant.entity';

@InputType()
export class CreateRestaurantInput extends PickType(Restaurant, [
  'name',
  'address',
  'coverImg',
]) {
  @Field(() => String)
  categoryName: string;
}
///Restaurnt Entity에서 PickType로 name, address, coverImg 세개를
///초이스 한다.
///추가로 categoryName를 입력받아, 있는 카테고리이면, 연결하고,
///없는 카테고리이면, 새로 카테고리를 만든다.

@ObjectType()
export class CreateRestaurantOutput extends MutationOutput {}

2. restaurant.resolver.ts

  @Mutation(() => CreateRestaurantOutput)
  @Role(['Owner']) /// user의 Role이 Owner만 아래의 함수를 사용할 수 있게 함.
  async createRestaurant(
    @AuthUser() authUser: User,
    @Args('input') createRestaurantInput: CreateRestaurantInput,
  ): Promise<CreateRestaurantOutput> {
    return this.restaurantService.createRestaurant(
      authUser,
      createRestaurantInput,  ///loggedInUser와 createResttaurant dto를 입력
    );
  }

3. restaurant.service.ts

@Injectable()
export class RestaurantService {
  constructor(
    @InjectRepository(Restaurant)
    private readonly restaurants: Repository<Restaurant>,
    @InjectRepository(Category)
    private readonly categories: Repository<Category>,
  ) {}

  async getOrCreateCategory(name: string): Promise<Category> {
    const categoryName = name.trim().toLowerCase();
    ///CreateRestaurantInput의 categoryName을 입력받아 앞,뒤 공백을 없애고(trim), 
    ///소문자로 다 만들어줌(toLowerCase)
    
    const categorySlug = categoryName.replace(/ /g, '-');
    ///반 공백에 - 을 넣어주는 categorySlug를 만듬(ac ac ac)=>(ac-ac-ac)
    
    let category = await this.categories.findOneBy({ slug: categorySlug });
    ///category를 let으로 두어서, category entity의 slug에서
    ///CreateRestaurantInput에서 입력받아 만든 categorySlug로 
    ///category를 찾음.
    
    if (!category) {
      category = await this.categories.save(
        this.categories.create({ slug: categorySlug, name: categoryName }),
      );
    }
    ///기존에 존재하지 않는 카테고리이면 새로 만들어줌, 카테고리를
    
    return category;
    ///기존에 존재하는 카테고리이면, 그 카테고리를 return해줌.
  }
///categoryName을 입력받아서, category entity에서 카테고리가 있으면, 
///그기다 연결해 주고, 카테고리가 없으면, 새로 만들어 주는 함수임.

  async createRestaurant(
    owner: User,
    createRestaurantInput: CreateRestaurantInput,
  ): Promise<CreateRestaurantOutput> {
    try {
      const newRestaurant = this.restaurants.create(createRestaurantInput);
      ///dto에서 보내준 data로만 newRestaurant를 만든 다음, 아래에서,
      ///owner랑, category를 연결해 줌.
      
      newRestaurant.owner = owner; ///loggedInUser에서 보내준 user를 owner로
      const category = await this.getOrCreateCategory(
        createRestaurantInput.categoryName,
      );
      ///위에서 만든 함수로 카테고리를 만들어줌,
      
      newRestaurant.category = category;
      ///위에서 만든 카테고리를 새로만든 restaurant의 category로 연결해 줌,
      
      await this.restaurants.save(newRestaurant);
      ///newRestaurant를 save함.
      
      return {
        ok: true,
      };
      ///별 문제 없으면, true를 return함.
    } catch {
      return {
        ok: false,
        error: 'Could not create restaurant',
      };
    }
  }
  1. categoryname을 입력받아 category와 연결하는 부분은 잘 알아둘것,
  2. newRestaurnt에 AuthUser(owner)를 연결하는 부분을 잘 알아둘것.
profile
코딩하는초딩쌤

0개의 댓글