GraphQL 기본 두번째!

박상욱·2022년 3월 28일
0

GraphQL

목록 보기
4/4

GraphQL 은 타입시스템이며 타입 언어이고 이것을 GraphQL schema language라고 한다.

객체 타입과 필드

type CHaracter {
	name:String!
    appearsln:[Episode]!
}

객체 타입의 모든필드는 0개 이상의 인수를 가질 수 있다.

type Starshipt {
}

스키마 대부분의 타입은 일반 객체 타입이지만 스키마 내에는 특수한 두 가지 타입 (query, mutation)이 있습니다.

schema {
	query: Query
    mutation: Mutation
}

모든 GraphQL서비스느 query타입을 가지며 mutation타입은 가져도되고 안가져도 된다.

interface

특정 필드들을 포함하는 추상 타입

해당 인터페이스를 implemnets한 타입들이 가져야 할 필드 정의
lnline fragements가 interface나 union타입에서 쓰인다.
swapi의 node를 보면 알수있다.

interface Character {
  id: ID!
  name: String!
  friends: [Character]
  appearsIn: [Episode]!
}
type Human implements Character {
  id: ID!
  name: String!
  friends: [Character]
  appearsIn: [Episode]!
  starships: [Starship]
  totalCredits: Int
}

type Droid implements Character {
  id: ID!
  name: String!
  friends: [Character]
  appearsIn: [Episode]!
  primaryFunction: String
}

유니온 타입

유니온 타입은 인터페이스와 매우 유사하지만, 타입 간에 공통 필드를 특정하지 않습니다.

union SearchResult = Human | Droid | Starship

SearchResult 유니언 타입을 반환하는 필드를 쿼리하면, 어떤 필드라도 쿼리할 수 있는 조건부 프래그먼트를 사용해야합니다.

{
  search(text: "an") {
    ... on Human {
      name
      height
    }
    ... on Droid {
      name
      primaryFunction
    }
    ... on Starship {
      name
      length
    }
  }
}

입력 타입

뮤테이션에서 특히 유용하다.
뮤테이션은 생성될 전체 객체를 전달하고자 할 수 있습니다.
GraphQL 스키마 언어에서 입력 타입은 일반 객체 타입과 정확히 같지만, type 대신 input 을 사용합니다.

#input type
input ReviewInput {
  stars: Int!
  commentary: String
}

#operate code
mutation CreateReviewForEpisode($ep: Episode!, $review: ReviewInput!) {
  createReview(episode: $ep, review: $review) {
    stars
    commentary
  }
}

#variables
{
  "ep": "JEDI",
  "review": {
    "stars": 5,
    "commentary": "This is a great movie!"
  }
}
profile
개발자

0개의 댓글