Sha256: af701e9f69b66d242c8b3c3338b2f97f7f62d509a2c79bd21f0d44621be0d032

Contents?: true

Size: 1.85 KB

Versions: 13

Compression:

Stored size: 1.85 KB

Contents

module GraphQL::Batch
  class Executor
    THREAD_KEY = :"#{name}.batched_queries"
    private_constant :THREAD_KEY

    class << self
      def current
        Thread.current[THREAD_KEY]
      end

      def current=(executor)
        Thread.current[THREAD_KEY] = executor
      end

      def start_batch(executor_class)
        executor = Thread.current[THREAD_KEY] ||= executor_class.new
        executor.increment_level
      end

      def end_batch
        executor = current
        unless executor
          raise NoExecutorError, 'Cannot end a batch without an Executor.'
        end
        return unless executor.decrement_level < 1
        self.current = nil
      end
    end

    # Set to true when performing a batch query, otherwise, it is false.
    #
    # Can be used to detect unbatched queries in an ActiveSupport::Notifications.subscribe block.
    attr_reader :loading

    def initialize
      @loaders = {}
      @loading = false
      @nesting_level = 0
    end

    def loader(key)
      @loaders[key] ||= yield.tap do |loader|
        loader.executor = self
        loader.loader_key = key
      end
    end

    def resolve(loader)
      was_loading = @loading
      @loading = true
      loader.resolve
    ensure
      @loading = was_loading
    end

    def tick
      resolve(@loaders.shift.last)
    end

    def wait_all
      tick until @loaders.empty?
    end

    def clear
      @loaders.clear
    end

    def increment_level
      @nesting_level += 1
    end

    def decrement_level
      @nesting_level -= 1
    end

    def around_promise_callbacks
      # We need to set #loading to false so that any queries that happen in the promise
      # callback aren't interpreted as being performed in GraphQL::Batch::Loader#perform
      was_loading = @loading
      @loading = false
      yield
    ensure
      @loading = was_loading
    end
  end
end

Version data entries

13 entries across 13 versions & 2 rubygems

Version Path
graphql-batch-0.6.0 lib/graphql/batch/executor.rb
graphql-batch-0.5.4 lib/graphql/batch/executor.rb
graphql-batch-0.5.3 lib/graphql/batch/executor.rb
graphql-batch-0.5.2 lib/graphql/batch/executor.rb
graphql-batch-0.5.1 lib/graphql/batch/executor.rb
graphql-batch-0.5.0 lib/graphql/batch/executor.rb
graphql-batch-0.4.3 lib/graphql/batch/executor.rb
graphql-batch-0.4.2 lib/graphql/batch/executor.rb
graphql-batch-0.4.1 lib/graphql/batch/executor.rb
graphql-batch-edge-0.4.0 lib/graphql/batch/executor.rb
graphql-batch-0.4.0 lib/graphql/batch/executor.rb
graphql-batch-0.3.10 lib/graphql/batch/executor.rb
graphql-batch-0.3.9 lib/graphql/batch/executor.rb