Class: Tiler::Widgets::ListQuery

Inherits:
Query::Base show all
Defined in:
lib/tiler/widgets/list.rb

Constant Summary collapse

VALID_ORDERS =
%w[asc desc].freeze

Constants inherited from Query::Base

Query::Base::SAFE_COLUMN_RE

Instance Attribute Summary

Attributes inherited from Query::Base

#config, #panel, #source

Instance Method Summary collapse

Methods inherited from Query::Base

#initialize

Constructor Details

This class inherits a constructor from Tiler::Query::Base

Instance Method Details

#callObject



9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
# File 'lib/tiler/widgets/list.rb', line 9

def call
  label_col = config["label_column"]
  agg       = config["aggregation"] || "count"
  val_col   = config["value_column"]
  limit     = (config["limit"] || 10).to_i.clamp(1, 100)
  order     = config["order"].to_s.downcase
  order     = "desc" unless VALID_ORDERS.include?(order)

  return { items: [] } if label_col.blank?

  labels = distinct_values(label_col)
  items = labels.map do |g|
    scope = apply_filters(
      source.data_records
            .then { |s| time_window_start ? s.where("recorded_at >= ?", time_window_start) : s }
            .where("json_extract(payload, ?) = ?", "$.#{label_col}", g.to_s)
    )
    { label: g, value: aggregate(scope, val_col, agg) }
  end
  items = items.sort_by { |i| i[:value].to_f }
  items = items.reverse if order == "desc"
  { items: items.first(limit) }
end