一个用于练习GraphQL的小脚本示例

为了尝试备受关注的 GraphQL,我添加了graphql gem以及graphiql-rails,并执行了相关的生成器。然后,我在yarn中还安装了apollo-boost、graphql-tag和graphql,并考虑为Vue安装了vue-apollo。但是,在这样操作的过程中,我变得很迷茫,不知道自己在做什么。因此,我回到了起点,开始研究如何单独简单地试用GraphQL。

只要手动安装 gem i graphql,下面的代码就可以在 Ruby 中立即执行。

对于 ping,返回 pong。

require "bundler/inline"

gemfile do
  gem "graphql"
end

GraphQL::VERSION                # => "1.8.5"

class QueryType < GraphQL::Schema::Object
  field :ping, String, null: false, description: "疎通確認"
  def ping
    "pong"
  end
end

class FooSchema < GraphQL::Schema
  query(QueryType)
end

FooSchema.execute("{ ping }").to_h # => {"data"=>{"ping"=>"pong"}}

返回 User.find(1) 的结果

require "bundler/inline"

gemfile do
  gem "graphql"
end

GraphQL::VERSION                # => "1.8.5"

class UserType < GraphQL::Schema::Object
  field :id,   ID,     null: false
  field :name, String, null: false
end

class QueryType < GraphQL::Schema::Object
  field :user, UserType, null: true do
    description "指定IDのユーザーを取得"
    argument :id, ID, "ユーザーID", required: true
  end

  def user(id:)
    Struct.new(:id, :name).new(id, "alice") # User.find(id) したことにする
  end
end

class FooSchema < GraphQL::Schema
  query(QueryType)
end

FooSchema.execute(<<~QUERY).to_h # => {"data"=>{"user"=>{"id"=>"1", "name"=>"alice"}}}
{
  user(id: 1) {
    id
    name
  }
}
QUERY