summaryrefslogtreecommitdiff
path: root/app/graphql/types/countable_connection_type.rb
blob: 0f24964daa675392740578c9b318618f40bbad5e (plain)
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

module Types
  # rubocop: disable Graphql/AuthorizeTypes
  class CountableConnectionType < GraphQL::Types::Relay::BaseConnection
    field :count, GraphQL::Types::Int, null: false,
          description: 'Total count of collection.'

    def count
      # rubocop: disable CodeReuse/ActiveRecord
      relation = object.items

      # sometimes relation is an Array
      relation = relation.reorder(nil) if relation.respond_to?(:reorder)
      # rubocop: enable CodeReuse/ActiveRecord

      if relation.try(:group_values)&.present?
        relation.size.keys.size
      else
        relation.size
      end
    end
  end
end