您好,登錄后才能下訂單哦!
在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進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。