我尝试使用GraphQL Ruby定义类型
尝试使用GraphQL Ruby进行类型定义
這篇文章是「試試GraphQL2-在Ruby中試試GraphQL」的續篇。
我參考過官方的以下頁面。
如果仔细阅读的话,仅凭这个就足够了,但由于一开始有个奇怪的误解,所以还是先把示例代码作为备忘录进行记录。
require 'graphql'
class User < GraphQL::Schema::Object
field :id, ID, null:true
field :name, String, null:true
end
class QueryType < GraphQL::Schema::Object
field :user, User, null:true
def user()
{'id'=>123, 'name'=>'Taro'}
end
end
class Schema < GraphQL::Schema
query QueryType
end
puts Schema.execute('query { user {name} }').to_json
$ bundle exec ruby type.rb
{"data":{"user":{"name":"Taro"}}}
请参考以下页面获取标量类型的相关信息。
与Sinatra整合在一起
source "https://rubygems.org"
gem "sinatra"
gem "sinatra-contrib"
gem 'rack-contrib'
gem "graphql"
require 'graphql'
require 'sinatra'
require 'sinatra/json'
require 'rack/contrib'
use Rack::PostBodyContentTypeParser
class User < GraphQL::Schema::Object
field :id, ID, null:true
field :name, String, null:true
end
class QueryType < GraphQL::Schema::Object
field :user, User, null:true
def user()
{'id'=>123, 'name'=>'Taro'}
end
end
class Schema < GraphQL::Schema
query QueryType
end
post '/graphql' do
json Schema.execute(params[:query], variables: params[:variables]).to_json
end
$ bundle exec ruby hoge.rb
[2019-06-09 21:20:09] INFO WEBrick 1.3.1
[2019-06-09 21:20:09] INFO ruby 2.3.3 (2016-11-21) [x86_64-linux-gnu]
== Sinatra (v2.0.5) has taken the stage on 4567 for development with backup from WEBrick
[2019-06-09 21:20:09] INFO WEBrick::HTTPServer#start: pid=2437 port=4567
$ curl -H 'Content-type: application/json' -X POST http://localhost:4567/graphql -d '{ "query" : "query { user {name} }" }'
"{\"data\":{\"user\":{\"name\":\"Taro\"}}}"%