Sua Blog

GraphQL

GraphQL

  • facebook에서 만든 쿼리언어
  • 웹 클라이언트가 데이터를 효율적으로 가져오는 것이 목적. 클라이언트가 원하는 정보 제공.
  • 여러 리소스를 단일 요청으로 가져올 수 있다.
  • 단 하나의 Endpoint

Query : read

특정 필드를 요청하고 데이터를 받아온다.

# request
{
  human(id: "1000") {
    name
    height(unit: FOOT)
  }
}

# response
{
  "data": {
    "human": {
      "name": "Luke Skywalker",
      "height": 5.6430448
    }
  }
}

Fragments : units

재사용 가능한 단위로 쿼리나 뮤테이션에 포함할 수 있다.

복잡한 데이터 요구 사항을 더 작은 단위로 사용할 수 있다.

# request
{
  leftComparison: hero(episode: EMPIRE) {
    ...comparisonFields
  }
  rightComparison: hero(episode: JEDI) {
    ...comparisonFields
  }
}

fragment comparisonFields on Character {
  name
  appearsIn
  friends {
    name
  }
}

# response
{
  "data": {
    "leftComparison": {
      "name": "Luke Skywalker",
      "appearsIn": [
        "NEWHOPE",
        "EMPIRE",
        "JEDI"
      ],
      "friends": [
        {
          "name": "Han Solo"
        },
        {
          "name": "Leia Organa"
        },
        {
          "name": "C-3PO"
        },
        {
          "name": "R2-D2"
        }
      ]
    },
    "rightComparison": {
      "name": "R2-D2",
      "appearsIn": [
        "NEWHOPE",
        "EMPIRE",
        "JEDI"
      ],
      "friends": [
        {
          "name": "Luke Skywalker"
        },
        {
          "name": "Han Solo"
        },
        {
          "name": "Leia Organa"
        }
      ]
    }
  }
}

Mutation: create, update, delete

GraphQL은 data fetching에 중점을 두고 있지만 플랫폼에서 데이터를 수정할 수 있는 방법이 필요하다.

쿼리와 마찬가지로 필드를 요청해서 업데이트 후 새 상태를 바로 받아올 수 있다.

# request
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!"
  }
}

# response
{
  "data": {
    "createReview": {
      "stars": 5,
      "commentary": "This is a great movie!"
    }
  }
}

Subscription: websoket

subscription으로 GraphQL 서버에서 실시간 데이터를 받을 수 있다.

# request
 subscription OnCommentAdded($postID: ID!) {
    commentAdded(postID: $postID) {
      id
      content
    }
  }

  # response
  {
  "data": {
    "commentAdded": {
      "id": "123",
      "content": "What a thoughtful and well written post!"
    }
  }
}

Schema

GraphQL 스키마의 가장 기본적인 구성 요소는 객체 타입이다. 스키마에는 어떤 종류의 객체를 반환할지, 어떤 인자를 받는지, 받는 데이터 형식이 정의되어있다.

type Character {
  name: String!
  appearsIn: [Episode]!
}
  • Character 는 GraphQL 객체 타입 이다. 즉, 필드가 있는 타입이다.
  • name 과 appearIn 은 Character 타입의 필드이다.
  • String! 은 필드가 non-nullable 이고 항상 값을 반환하는 것을 의미한다.
  • [Episode]! 는 Episode 객체의 배열(array)을 나타내고 또한 non-nullable 이기 때문에 appearIn 필드를 쿼리할 때 항상(0개 이상의 아이템을 가진) 배열을 기대할 수 있다.

Playground

Graphql API를 GUI로 보여주고 상호작용할 수 있는 IDE이다. 스키마와 Docs(query, mutation, subscription 확인)를 제공한다.

20

참고

graphql.org

apollo docs