summaryrefslogtreecommitdiff
path: root/lib/api/entities/issuable_entity.rb
blob: e2c674c0b8b9e87df9fd6642ae52ee7d60339f02 (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
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
# frozen_string_literal: true

module API
  module Entities
    class IssuableEntity < Grape::Entity
      expose :id, :iid
      expose(:project_id) { |entity| entity&.project.try(:id) }
      expose :title, :description
      expose :state, :created_at, :updated_at

      def presented
        lazy_issuable_metadata

        super
      end

      def issuable_metadata
        options.dig(:issuable_metadata, object.id) || lazy_issuable_metadata
      end

      protected

      # This method will preload the `issuable_metadata` for the current
      # entity according to the current top-level entity options, such
      # as the current_user.
      def lazy_issuable_metadata
        BatchLoader.for(object).batch(key: [current_user, :issuable_metadata]) do |models, loader, args|
          current_user = args[:key].first

          issuable_metadata = Gitlab::IssuableMetadata.new(current_user, models)
          metadata_by_id = issuable_metadata.data

          models.each do |issuable|
            loader.call(issuable, metadata_by_id[issuable.id])
          end
        end
      end

      private

      def current_user
        options[:current_user]
      end
    end
  end
end