NestJS&GraphQL CRUD 해보기

커피 내리는 그냥 사람·2021년 4월 19일
0

기업협업 인턴십

목록 보기
9/16

1. 데이터베이스 연동

  1. 연동되어 있는 데이터베이스 세팅에서 값을 맞춰준다. 여기서는 받은 데이터베이스에서 데이터베이스 이름과 비밀번호만 세팅 다시 해줬다.

  2. 에러난 것 해결 :

    er_not_supported_auth_mode: client does not support authentication protocol requested by server; consider upgrading mysql client

  • 해결 : 앞으로 쓸 패스워드로 초기화 하면 되는데 나는 그냥 ''으로 패스워드 초기화를 했다.
alter user 'einere'@'%' identified with mysql_native_password by 'mypassword';
  • 상황에 따라 DB내용이 초기화 될 수도 있다...ㅠ

2. Playground 활용하기(CRUD)

참고 링크

1. 클론 받은 자료에 npm install 다운받기

2. npm run start:dev 로 서버 실행

3. http://localhost:4000/graphql 들어가기

4. 실험해 본 내용

  • mutation (create)
mutation{
  createCat(input:{
    name :"Name",
    description : "Description"
  }
  ){
    ok
    error
    __typename
  }
}
  • get (read)
query{
  getCat(input:{
    id :1
  }){
    error
    ok
  }
}

resolver, service, dto, entity에 정해진대로밖에 입력이 안 된다.

5. 추가로 해본 것 : 브랜치 새로 개설 후 진행

전반적인 원리에 대한 생각 : resolver와 service간의 통신에서 dto 형태로 서버와 연결이라고 판단

  1. update
mutation{
  updateCat(input:{
    id :3,
    name : "냥이",
    description : "냥이입니다."
    # create와 달리 id가 들어간다.
  }){
    error
    ok
    __typename
  }
}
  • mysql에 연결된 3번 데이터 바꾸기

Input -> objectType(output) 으로 생각하기

이를 위해 만든 다른 코드
<update-cat_dto.ts>

import { InputType, ObjectType, PartialType, PickType } from "@nestjs/graphql";
import { CoreOutput } from "src/common/dtos/output.dto";
import { Cat } from "../entities/cat.entity";

@InputType()
export class UpdateCatInput extends PickType(Cat, ["id", "name", "description"]){
    // PickType으로 원하는 자료를 가져온다.
}

@ObjectType()
export class UpdateCatOutput extends CoreOutput {

}

<cats.resolver.ts>

    @Mutation(returns => UpdateCatOutput)
    async updateCat(
        @Args('input') updateCatInput: UpdateCatInput
    ): Promise<UpdateCatOutput>{
        return this.catService.updateCat(updateCatInput)
    }

<cats.service.ts>

async updateCat(updateCatInput: UpdateCatInput): Promise<UpdateCatOutput> {
        try {

            /* update Cat */
            await this.cats.update(updateCatInput.id, {...updateCatInput});


            return {
                ok: true
            }

        }catch(e){
            console.log(e);

            return {
                ok: false,
                error: "Cannot update cat"
            }
        }
    }

  1. delete
mutation{
  deleteCat(input:{
    id : 2,
    name : "Nero",
    description : "Description"
  }){
    error
    ok
    __typename
  }
}

어떤 걸 지울지 확인

앞에 내용은 delete로만 바꾸면 됨.

profile
커피 내리고 향 맡는거 좋아해요. 이것 저것 공부합니다.

0개의 댓글