Class: GraphQL::Streaming::StreamCollector

Inherits:
Object
  • Object
show all
Defined in:
lib/graphql/streaming/stream_collector.rb

Overview

Send patches by calling ‘stream.write` Each patch is serialized as JSON and delimited with “nn”

Examples:

Streaming a response with Rails

class ChunkedGraphqlsController < ApplicationController
  include ActionController::Live

  def create
    # initialize the collector with `response.stream`
    context = {
      collector: StreamCollector.new(response.stream)
    }

    Schema.execute(query_string, variables: variables, context: context)

    # close the stream when the query is done:
    response.stream.close
  end
end

Constant Summary collapse

DELIMITER =
"\n\n"

Instance Method Summary collapse

Constructor Details

#initialize(stream) ⇒ StreamCollector

Returns a new instance of StreamCollector.

Parameters:

  • A (<#write(String)>)

    stream to write patches to



26
27
28
29
# File 'lib/graphql/streaming/stream_collector.rb', line 26

def initialize(stream)
  @stream = stream
  @first_patch = true
end

Instance Method Details

#patch(path:, value:) ⇒ Object

Implement the collector API for DeferredExecution



32
33
34
35
36
37
38
39
40
41
# File 'lib/graphql/streaming/stream_collector.rb', line 32

def patch(path:, value:)
  patch_string = JSON.dump({path: path, value: value})

  if @first_patch
    @first_patch = false
    @stream.write(patch_string)
  else
    @stream.write(DELIMITER + patch_string)
  end
end