Class: GraphQL::Api::Resolvers::ModelListQuery

Inherits:
Object
  • Object
show all
Defined in:
lib/graphql/api/resolvers/model_list_query.rb

Instance Method Summary collapse

Constructor Details

#initialize(model) ⇒ ModelListQuery

Returns a new instance of ModelListQuery.



5
6
7
8
# File 'lib/graphql/api/resolvers/model_list_query.rb', line 5

def initialize(model)
  @model = model
  @policy_class = "#{model.name}Policy".safe_constantize
end

Instance Method Details

#call(obj, args, ctx) ⇒ Object



10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# File 'lib/graphql/api/resolvers/model_list_query.rb', line 10

def call(obj, args, ctx)
  if @model.respond_to?(:graph_where)
    @model.graph_where(args, ctx)
  else
    eager_load = []
    ctx.irep_node.children.each do |child|
      eager_load << child[0] if @model.reflections.find { |name, _| name == child[0] }
    end

    query_args = args.to_h
    query_args.delete('limit')

    q = @model.where(query_args)
    q.eager_load(*eager_load) if eager_load.any?
    results = q.limit(args[:limit] || 30)

    if @policy_class
      results.each do |res|
        policy = @policy_class.new(ctx, res)
        return policy.unauthorized! unless policy.read?
      end
    end
    
    results
  end
end