溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

在Ruby中使用GraphQL

發布時間:2024-04-19 15:09:23 來源:億速云 閱讀:60 作者:小樊 欄目:編程語言

在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來與應用程序交互了??梢允褂肎raphiQL等工具來測試GraphQL端點。

向AI問一下細節

免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI

亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女