Home > front end >  graphql-ruby: how to get current user IP inside QueryType?
graphql-ruby: how to get current user IP inside QueryType?

Time:03-25

How to get current user's IP address inside QueryType? For example here:

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

CodePudding user response:

You need to pass in a context to graphql.

Here's an example:

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

Then,

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
  • Related