BigW Consortium Gitlab

environment_serializer.rb 1.32 KB
Newer Older
1
class EnvironmentSerializer < BaseSerializer
2
  Item = Struct.new(:name, :size, :latest)
3

4
  entity EnvironmentEntity
5

6
  def within_folders
7 8 9
    tap { @itemize = true }
  end

10
  def with_pagination(request, response)
11
    tap { @paginator = Gitlab::Serializer::Pagination.new(request, response) }
12 13
  end

14 15 16 17
  def itemized?
    @itemize
  end

18
  def paginated?
19
    @paginator.present?
20 21
  end

22 23 24 25 26 27 28 29
  def represent(resource, opts = {})
    if itemized?
      itemize(resource).map do |item|
        { name: item.name,
          size: item.size,
          latest: super(item.latest, opts) }
      end
    else
30 31
      resource = @paginator.paginate(resource) if paginated?

32 33 34 35 36 37 38
      super(resource, opts)
    end
  end

  private

  def itemize(resource)
39 40 41 42 43 44 45 46 47
    items = resource.order('folder_name ASC')
      .group('COALESCE(environment_type, name)')
      .select('COALESCE(environment_type, name) AS folder_name',
              'COUNT(*) AS size', 'MAX(id) AS last_id')

    # It makes a difference when you call `paginate` method, because
    # although `page` is effective at the end, it calls counting methods
    # immediately.
    items = @paginator.paginate(items) if paginated?
48

49
    environments = resource.where(id: items.map(&:last_id)).index_by(&:id)
50

51 52
    items.map do |item|
      Item.new(item.folder_name, item.size, environments[item.last_id])
53 54
    end
  end
55
end