Rails에서 GraphQL 사용 해서 DB수정 하기

rails·2021년 10월 26일
0

Rails 튜토리얼

목록 보기
2/11

※ 이전 포스팅에서 작성한 GraphQL 사용하기 포스팅에서 이어집니다.

Rails에서 GraphQL 사용 해서 DB수정 하기

시작점
app/graphql/types/mutation_type.rb

이는 모든 GraphQL 뮤테이션 쿼리의 토대가 된다.

test_field는 자동 생성 되어 있다. 원하는 뮤테이션을 추가 한 뒤에는 삭제 하면 된다.

베이스 뮤테이션은 위와 같이 /app/graphql/mutations/base_mutations.rb에 정의 되어 있다.

이제 새 커스텀 뮤테이션을 추가 할 것이다.
링크를 생성 하는 쿼리를 만들 것이므로 이름을 create_link로 지어보자.
/app/graphql/mutations/create_link.rb 파일을 생성 해준다.

그 후에 mutation type 에서 기존 코드를 삭제 하고 아래처럼 구성 하자.

module Types
  class MutationType < BaseObject
    field :create_link, mutation: Mutations::CreateLink
  end
end

이제 잘 실행 되는 것을 플레이 그라운드에서 확인 해보자.
http://localhost:3000/graphiql URL을 웹 브라우저로 연다.

그리고 아래와 같이 새 링크를 만들 정보를 넘겨 보자.
문자열은 반드시 이중따옴표로 감싸 주어야 한다.

mutation {
  createLink(
    url: "http://www.google.com",
    description: "this is google",
  ) {
    id
    url
    description
  }
}

실행 해보니 에러가 발생 한다. 친절 하게도 에러의 종류와 발생 위치를 구체적으로 알려준다.

{
  "errors": [
    {
      "message": "Field 'createLink' is missing required arguments: input",
      "locations": [
        {
          "line": 3,
          "column": 3
        }
      ],
      "path": [
        "mutation",
        "createLink"
      ],
      "extensions": {
        "code": "missingRequiredArguments",
        "className": "Field",
        "name": "createLink",
        "arguments": "input"
      }
    },
    {
      "message": "Field 'createLink' doesn't accept argument 'url'",
      "locations": [
        {
          "line": 4,
          "column": 5
        }
      ],
      "path": [
        "mutation",
        "createLink",
        "url"
      ],
      "extensions": {
        "code": "argumentNotAccepted",
        "name": "createLink",
        "typeName": "Field",
        "argumentName": "url"
      }
    },
    {
      "message": "Field 'createLink' doesn't accept argument 'description'",
      "locations": [
        {
          "line": 5,
          "column": 5
        }
      ],
      "path": [
        "mutation",
        "createLink",
        "description"
      ],
      "extensions": {
        "code": "argumentNotAccepted",
        "name": "createLink",
        "typeName": "Field",
        "argumentName": "description"
      }
    }
  ]
}

아규먼트가 부족하다는데 그럴리가 없다.
의심 가는 포인트를 추적 해보니 내가 작성하지 않은 코드에 해당 input아규먼트를 요구하는 부분이 있을 것이라고 생각 되었다.

코드를 자세히 살펴보니 base_mutation.rb에서 RelayClassicMutation클래스를 상속 받고 있었다. (헬로월드 만들 때 기본값)

  class BaseMutation < GraphQL::Schema::RelayClassicMutation
  ...

RelayClassicMutation클래스에서 input 아규먼트를 요구함이 명백해 보였다.

base_mutation.rb파일을 아래와같이 Mutation클래스를 상속 받도록 변경 해주자.

module Mutations
  class BaseMutation < GraphQL::Schema::Mutation
    null false
  end
end

저장후 플레이그라운드를 실행 해보면 아래와 같이 문제 없이 리턴 되는 것을 알 수 있다.

레일즈 서버 로그를 확인 해보면 INSERT쿼리도 잘 실행 되었다.

profile
rails

0개의 댓글