Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Question] How to use JSON Patch with SSE in Rails Controller? #13

Open
HLFH opened this issue Jun 7, 2018 · 0 comments
Open

[Question] How to use JSON Patch with SSE in Rails Controller? #13

HLFH opened this issue Jun 7, 2018 · 0 comments

Comments

@HLFH
Copy link

HLFH commented Jun 7, 2018

Hi @tenderlove ,

In the controller:

module Api::V1
  class TestController < ApiController
    include ActionController::Live

    def ticker
      response.headers['Content-Type'] = 'text/event-stream'
      sse = Ticker::SSE.new(response.stream)
      begin
        loop do
          test = Test.desc
          a = test.second.as_json(except: ["created_at", "updated_at", "_id"]) 
          b = test.first.as_json(except: ["created_at", "updated_at", "_id"])
          diff = JsonDiff.generate(a, b)
         patch = Hana::Patch.new [diff]
         #what to do then with `patch.apply` and `sse.write`?
          sse.write(json)
        end
      rescue IOError
        logger.info 'Client disconnects causes IOError on write'
      ensure
        sse.close
      end
    end
  end
end

In app/lib/ticker/sse.rb

module Ticker
  class SSE
    def initialize(io)
      @io = io
    end

    def write(object, options = {})
      options.each do |k,v|
        @io.write("#{k}: #{v}\n")
      end
      @io.write("data: #{JSON.dump(object)}\n\n")
    end

    def close
      @io.close
    end
  end
end

Many thanks,

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant