graphql-ruby:如何在 QueryType 中获取当前用户 IP?

graphql-ruby: how to get current user IP inside QueryType?

如何在QueryType中获取当前用户的IP地址?例如 这里:

class QueryType < GraphQL::Schema::Object
  description "The query root of this schema"

  field :post, PostType, "Find a post by ID" do
    argument :id, ID
  end

  def post(id:)
    # I need to get user's IP here
    Post.find(id)
  end
end

你需要传入一个context给graphql。

这是一个例子:

class GraphqlController < ApplicationController
  def execute
    variables = prepare_variables(params[:variables])
    query = params[:query]
    operation_name = params[:operationName]
    context = {
      current_user: current_user,
      ip: request.remote_ip
    }
    result = YourSchema.execute(query, variables: variables, context: context, operation_name: operation_name)
    render json: result
  rescue StandardError => e
    raise e unless Rails.env.development?
    handle_error_in_development(e)
  end

然后,

class QueryType < GraphQL::Schema::Object
  description "The query root of this schema"

  field :post, PostType, "Find a post by ID" do
    argument :id, ID
  end

  def post(id:)
    # I need to get user's IP here
    # => context[:ip]
    Post.find(id)
  end
end