如何在Graphql解析器中传递:current_user

时间:2018-08-21 22:21:18

标签: ruby-on-rails ruby-on-rails-5 graphql graphql-ruby

我有QueryType

Types::QueryType = GraphQL::ObjectType.define do
  name 'Query'

  field :allProjects, function: Resolvers::Projects
end

还有这样的解析器

require 'search_object/plugin/graphql'

module Resolvers
  class Projects
    include SearchObject.module(:graphql)

    type !types[Types::ProjectType]

    scope { Project.all }

    ProjectFilter = GraphQL::InputObjectType.define do
      name 'ProjectFilter'

      argument :OR, -> { types[ProjectFilter] }
      argument :description_contains, types.String
      argument :title_contains, types.String
    end

    option :filter, type: ProjectFilter, with: :apply_filter
    option :first, type: types.Int, with: :apply_first
    option :skip, type: types.Int, with: :apply_skip

    def apply_first(scope, value)
      scope.limit(value)
    end

    def apply_skip(scope, value)
      scope.offset(value)
    end

    def apply_filter(scope, value)
      branches = normalize_filters(value).reduce { |a, b| a.or(b) }
      scope.merge branches
    end

    def normalize_filters(value, branches = [])
      scope = Project.all
      scope = scope.where('description ILIKE ?', "%#{value['description_contains']}%") if value['description_contains']
      scope = scope.where('title ILIKE ?', "%#{value['title_contains']}%") if value['title_contains']
      branches << scope

      value['OR'].reduce(branches) { |s, v| normalize_filters(v, s) } if value['OR'].present?
      branches
    end
  end
end

我想访问解析器中的current_user,以便可以访问current_user.projects而不是Project.all。我对graphql和学习非常陌生。

一切正常,但是我只需要了解有关如何使解析器中的ctx变老的整个流程。

1 个答案:

答案 0 :(得分:2)

首先,您需要在上下文中设置current_user。这发生在您的GraphqlController中。

class GraphqlController < ApplicationController
  before_action :authenticate_user!

  def execute
    variables = ensure_hash(params[:variables])
    query = params[:query]
    operation_name = params[:operationName]
    context = {
      current_user: current_user,
    }
    result = HabitTrackerSchema.execute(query, variables: variables, context: context, operation_name: operation_name)
    render json: result
  rescue => e
    raise e unless Rails.env.development?
    handle_error_in_development e
  end

  # ...
end

完成后,您只需编写以下命令即可从查询(或变异)中访问current_user

context[:current_user]

为使事情变得更加简单,您可以向current_userTypes::BaseObject)添加app/graphql/types/base_object.rb方法,然后可以从{{1 }}方法。

current_user