# frozen_string_literal: true module GraphQL module Streaming # Send patches by calling `stream.write` # Each patch is serialized as JSON and delimited with "\n\n" # @example 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 class StreamCollector DELIMITER = "\n\n" # @param [<#write(String)>] A stream to write patches to def initialize(stream) @stream = stream @first_patch = true end # Implement the collector API for DeferredExecution 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 end end end