summaryrefslogtreecommitdiff
path: root/app/graphql/types/countable_connection_type.rb
blob: 2538366b7862d6039769fe5f8be37d6292c3c44e (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, Integer, 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