Module: Graphoid::Filters

Defined in:
lib/graphoid/definitions/filters.rb

Constant Summary collapse

LIST =
{}

Class Method Summary collapse

Class Method Details

.generate(model) ⇒ Object



8
9
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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
# File 'lib/graphoid/definitions/filters.rb', line 8

def generate(model)
  LIST[model] ||= GraphQL::InputObjectType.define do
    name("#{Utils.graphqlize(model.name)}Filter")
    description("Generated model filter for #{model.name}")

    Attribute.fields_of(model).each do |field|
      type = Graphoid::Mapper.convert(field)
      name = Utils.camelize(field.name)

      argument name, type

      m = LIST[model]
      argument(:OR,  -> { types[m] })
      argument(:AND, -> { types[m] })

      operators = %w[lt lte gt gte contains not]
      operators.push('regex') if Graphoid.configuration.driver == :mongoid

      operators.each do |suffix|
        argument "#{name}_#{suffix}", type
      end

      %w[in nin].each do |suffix|
        argument "#{name}_#{suffix}", types[type]
      end
    end

    Relation.relations_of(model).each do |name, relation|
      relation_class = relation.class_name.safe_constantize
      next unless relation_class

      relation_filter = LIST[relation_class]
      next unless relation_filter

      relation_name = Utils.camelize(name)

      if Relation.new(relation).many?
        %w[some none every].each do |suffix|
          argument "#{relation_name}_#{suffix}", relation_filter
        end
      else
        argument relation_name.to_s, relation_filter
      end
    end
  end
end