summaryrefslogtreecommitdiff
path: root/lib/gitlab/graphql/lazy.rb
blob: 3563504226c43d7c1a39c56ba8c2f9ac0041ee0e (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
47
48
49
50
51
52
53
# frozen_string_literal: true

module Gitlab
  module Graphql
    class Lazy
      include Gitlab::Utils::StrongMemoize

      def initialize(&block)
        @proc = block
      end

      def force
        strong_memoize(:force) { self.class.force(@proc.call) }
      end

      def then(&block)
        self.class.new { yield force }
      end

      def catch(error_class = StandardError, &block)
        self.class.new do
          force
        rescue error_class => e
          yield e
        end
      end

      # Force evaluation of a (possibly) lazy value
      def self.force(value)
        case value
        when ::Gitlab::Graphql::Lazy
          value.force
        when ::BatchLoader::GraphQL
          value.sync
        when ::Gitlab::Graphql::Deferred
          value.execute
        when ::GraphQL::Execution::Lazy
          value.value # part of the private api, but we can force this as well
        when ::Concurrent::Promise
          value.execute if value.state == :unscheduled

          value.value # value.value(10.seconds)
        else
          value
        end
      end

      def self.with_value(unforced, &block)
        self.new { unforced }.then(&block)
      end
    end
  end
end