1.9' 然后在終端運行bundle install來安裝..."/>
您好,登錄后才能下訂單哦!
在Ruby中使用GraphQL,可以使用graphql-ruby gem來實現(xiàn)。首先需要安裝gem:
gem 'graphql', '~> 1.9'
然后在終端運行bundle install
來安裝gem。
接下來,創(chuàng)建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
然后創(chuàng)建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"
創(chuàng)建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
現(xiàn)在就可以通過發(fā)送GraphQL查詢和mutation來與應用程序交互了。可以使用GraphiQL等工具來測試GraphQL端點。
免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。