在Ruby中使用GraphQL,可以使用graphql-ruby gem来实现。首先需要安装gem:
gem 'graphql', '~> 1.9'
然后在终端运行bundle install
来安装gem。
接下来,创建GraphQL schema并定义查询和mutation:
# app/graphql/types/query_type.rb
Types::QueryType = GraphQL::ObjectType.define do
name "Query"
field :all_users, !types[Types::UserType] do
resolve -> (obj, args, ctx) { User.all }
end
end
# app/graphql/types/mutation_type.rb
Types::MutationType = GraphQL::ObjectType.define do
name "Mutation"
field :create_user, Types::UserType do
argument :name, !types.String
argument :email, !types.String
resolve -> (obj, args, ctx) { User.create(name: args[:name], email: args[:email]) }
end
end
# app/graphql/types/user_type.rb
Types::UserType = GraphQL::ObjectType.define do
name "User"
field :id, !types.ID
field :name, !types.String
field :email, !types.String
end
然后创建GraphQL schema:
# app/graphql/schema.rb
Schema = GraphQL::Schema.define do
query Types::QueryType
mutation Types::MutationType
end
最后,将GraphQL endpoint添加到Rails应用中:
# config/routes.rb
post "/graphql", to: "graphql#execute"
创建GraphQL controller:
# app/controllers/graphql_controller.rb
class GraphqlController < ApplicationController
def execute
result = Schema.execute(params[:query], variables: params[:variables])
render json: result
end
end
现在就可以通过发送GraphQL查询和mutation来与应用程序交互了。可以使用GraphiQL等工具来测试GraphQL端点。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。