Read about our upcoming Code of Conduct on this issue

deployments_finder.rb 1.8 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
# frozen_string_literal: true

class DeploymentsFinder
  attr_reader :project, :params

  ALLOWED_SORT_VALUES = %w[id iid created_at updated_at ref].freeze
  DEFAULT_SORT_VALUE = 'id'.freeze

  ALLOWED_SORT_DIRECTIONS = %w[asc desc].freeze
  DEFAULT_SORT_DIRECTION = 'asc'.freeze

  def initialize(project, params = {})
    @project = project
    @params = params
  end

  def execute
    items = init_collection
    items = by_updated_at(items)
    sort(items)
  end

  private

25
  # rubocop: disable CodeReuse/ActiveRecord
26
  def init_collection
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
    project
      .deployments
      .includes(
        :user,
        environment: [],
        deployable: {
          job_artifacts: [],
          pipeline: {
            project: {
              route: [],
              namespace: :route
            }
          },
          project: {
            namespace: :route
          }
        }
      )
45
  end
46
  # rubocop: enable CodeReuse/ActiveRecord
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64

  # rubocop: disable CodeReuse/ActiveRecord
  def sort(items)
    items.order(sort_params)
  end
  # rubocop: enable CodeReuse/ActiveRecord

  def by_updated_at(items)
    items = items.updated_before(params[:updated_before]) if params[:updated_before].present?
    items = items.updated_after(params[:updated_after]) if params[:updated_after].present?

    items
  end

  def sort_params
    order_by = ALLOWED_SORT_VALUES.include?(params[:order_by]) ? params[:order_by] : DEFAULT_SORT_VALUE
    order_direction = ALLOWED_SORT_DIRECTIONS.include?(params[:sort]) ? params[:sort] : DEFAULT_SORT_DIRECTION

65
66
67
68
    { order_by => order_direction }.tap do |sort_values|
      sort_values['id'] = 'desc' if sort_values['updated_at']
      sort_values['id'] = sort_values.delete('created_at') if sort_values['created_at'] # Sorting by `id` produces the same result as sorting by `created_at`
    end
69
70
  end
end