Module: DashApi::Query

Defined in:
app/services/dash_api/query.rb

Constant Summary collapse

PER_PAGE =
20
SORT_DIRECTIONS =
['asc', 'desc']
DELIMITER =
":"
OPERATORS =
{
  "gt": ">",
  "gte": ">=",
  "lt": "<",
  "lte": "<=",
  "eq": "=",
  "neq": "!="
}

Class Method Summary collapse

Class Method Details

.format_filter(filter_param) ⇒ Object



85
86
87
88
89
90
91
# File 'app/services/dash_api/query.rb', line 85

def self.format_filter(filter_param)
  field, rel, value = filter_param.split(DELIMITER)
  rel = "eq" unless OPERATORS.keys.include?(rel.to_sym)      
  operator = OPERATORS[rel.to_sym] || '='   
  condition = "#{field} #{operator} ?"
  [condition, value]
end

.parse(params) ⇒ Object

perform DashApi::Query is a helper module which parses URL parameters passed to a Rails Controller into attributes used to query a DashTable



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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
# File 'app/services/dash_api/query.rb', line 25

def self.parse(params)       
  
  keywords = params[:keywords]
  
  if params[:select]
    select_fields = params[:select]&.split(',')
  end 
  
  if params[:order]        
    sort_by, sort_direction = params[:order].split(DELIMITER)        
    sort_direction = "desc" if sort_direction and !SORT_DIRECTIONS.include?(sort_direction)
    order = { "#{sort_by}": sort_direction }
  end 

  if params[:includes] 
    associations = params[:includes].split(",").map(&:strip)
  end 

  filters = []      
  if params[:filters]
    params[:filters].split(',').each do |filter_param|             
      filters << format_filter(filter_param)
    end  
  end 

  stats = nil
  if params[:max]
    stats = {maximum: params[:max]}
  end 

  if params[:min]
    stats = {minimum: params[:min]}
  end 

  if params[:avg]
    stats = {average: params[:avg]}
  end 

  if params[:count]
    stats = {count: params[:count]}
  end 


  page = params[:page]&.to_i || 1 
  per_page = params[:per_page]&.to_i || PER_PAGE 

  {
    associations: associations,
    filters: filters,
    keywords: keywords,
    order: order,
    page: page,
    per_page: per_page, 
    select_fields: select_fields,        
    sort_by: sort_by,
    sort_direction: sort_direction,        
    stats: stats
  }
end