miyohideの日記

技術的なメモなどを記しています

2023年8月9日

RubyでのGraphQL Client graphql-client gem

github.com

使い方はReadmeにあるものをそのまままねるとOK。

require "graphql/client"
require "graphql/client/http"

HTTP = GraphQL::Client::HTTP.new('http://localhost:3000/graphql')
Schema = GraphQL::Client.load_schema(HTTP)
Client = GraphQL::Client.new(schema: Schema, execute: HTTP)


MyQuery = Client.parse <<-'GRAPHQL'
{
  runlogs {
    id
    distance
  }
}
GRAPHQL

Client.query(MyQuery)
````

`MyQuery`は定数でないとダメ。例えば`a`とかにすると、`Client.query(a)`を実行時に以下のメッセージを吐く。

in `query': expected definition to be assigned to a static constant https://git.io/vXXSE (GraphQL::Client::DynamicQueryError)

説明は以下を参照。

[https://github.com/github/graphql-client/blob/master/guides/dynamic-query-error.md:embed:cite]