Class: Maestrano::Api::BaseResource

Inherits:
JSONAPI::Resource
  • Object
show all
Includes:
Pundit::Resource
Defined in:
app/resources/maestrano/api/base_resource.rb

Constant Summary collapse

API_SQL_OPERATOR_MAPPING =
{
  gt: '>',
  gte: '>=',
  lt: '<',
  lte: '<=',
  ne: '<>',
  like: 'LIKE'
}.freeze

Class Method Summary collapse

Class Method Details

.all_filtersObject



16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
# File 'app/resources/maestrano/api/base_resource.rb', line 16

def self.all_filters
  # Skipping if there is no tables as calling columns_hash in attribute_type is causing issue
  return unless tables_exists?

  _attributes.keys.each do |attribute|
    type = attribute_type(attribute)
    if type == :boolean
      # https://github.com/cerebris/jsonapi-resources/issues/852
      # make sure filter applied on boolean works
      filter(attribute, verify: :verify_boolean_filter)
    else
      filter(attribute)
    end
  end
  generate_composite_filters
end

.attribute_type(attribute) ⇒ Object



56
57
58
59
60
# File 'app/resources/maestrano/api/base_resource.rb', line 56

def self.attribute_type(attribute)
  _model_class.columns_hash[attribute.to_s]&.type || :string
rescue
  :string
end

.generate_composite_filtersObject



33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
# File 'app/resources/maestrano/api/base_resource.rb', line 33

def self.generate_composite_filters
  _allowed_filters.keys.each do |key|
    # iterating through all the api operator and adding them as custom filter
    # name.gt, name.like etc...
    next unless _model_class

    field = "#{_model_class.table_name}.#{key}"

    API_SQL_OPERATOR_MAPPING.each do |api_operator, sql_operator|
      filter "#{key}.#{api_operator}",
             apply: ->(records, value, _options) { records.where("#{field} #{sql_operator} ?", value[0]) }
    end
    filter "#{key}.none",
           apply: ->(records, value, _options) { records.where("#{field} IS NULL") }
    filter "#{key}.not",
           apply: ->(records, value, _options) { value[0] ? records.where("#{field} <> ?", value[0]) : records.where("#{field} IS NOT NULL") }
    filter "#{key}.nin",
           apply: ->(records, value, _options) { records.where("#{field} NOT IN (?)", value) }
    filter "#{key}.in",
           apply: ->(records, value, _options) { records.where("#{field} IN (?)", value) }
  end
end

.tables_exists?Boolean

If the code is loaded before table are created (during a schema:load for example) this will return false

Returns:

  • (Boolean)


63
64
65
66
# File 'app/resources/maestrano/api/base_resource.rb', line 63

def self.tables_exists?
  @tables_exists = ActiveRecord::Base.connection.table_exists?('users') if @tables_exists.nil?
  @tables_exists
end