Module: Istox::ResultHandler

Defined in:
lib/istox/helpers/result_handler.rb

Class Method Summary collapse

Class Method Details

.order(query:, meta:) ⇒ Object



15
16
17
18
19
20
21
22
23
24
25
26
27
28
# File 'lib/istox/helpers/result_handler.rb', line 15

def self.order(query:, meta:)
  return query if meta.blank? || meta.sorts.blank?

  meta.sorts.each do |sort|
    # to prevent sql injection
    # sort.field should contains only alphabet and nothing else
    raise StandardError, 'POSSIBLE_SQL_INJECTION' unless validate_column_name(sort.field)
    # sort.order can only be asc or desc
    raise StandardError, 'POSSIBLE_SQL_INJECTION' unless %w[asc desc].include?(sort.order.downcase)

    query = query.order("#{sort.field.downcase} #{sort.order.upcase}")
  end
  query
end

.paginate(query:, meta:) ⇒ Object



30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
# File 'lib/istox/helpers/result_handler.rb', line 30

def self.paginate(query:, meta:)
  current_page = meta.page
  current_page = 1 if current_page <= 0

  offset = (current_page - 1) * meta.limit
  total = query.count(:all)
  data = query.limit(meta.limit).offset(offset)

  page_count = (total + meta.limit - 1) / meta.limit

  OpenStruct.new(
    data: data,
    pagination: {
      page: current_page,
      limit: meta.limit,
      previousPage: current_page - 1,
      currentPage: current_page,
      nextPage: current_page < page_count ? current_page + 1 : 0,
      pageCount: page_count,
      totalCount: total
    }
  )
end

.process(query:, meta:, exclude_order: false, exclude_paginate: false) ⇒ Object

main method to be called, suggested to always use this method and not individual method below



4
5
6
7
8
9
10
11
12
13
# File 'lib/istox/helpers/result_handler.rb', line 4

def self.process(query:, meta:, exclude_order: false, exclude_paginate: false)
  query = order(query: query, meta: meta) unless exclude_order

  # if never set limit, means no pagination is needed
  return OpenStruct.new(data: query.all, pagination: nil) if meta.limit.blank? || meta.limit.zero?

  return paginate(query: query, meta: meta) unless exclude_paginate

  query
end