Last active
November 28, 2017 23:23
-
-
Save jamiehodge/5676442 to your computer and use it in GitHub Desktop.
Server Side Events, Sequel and Postgres LISTEN/NOTIFY
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'sequel' | |
DB ||= Sequel.connect ENV['DATABASE_URL'] | |
class Resource < Sequel::Model | |
include Sequel.inflections | |
def after_save | |
db.notify channel | |
end | |
def listen | |
db.listen channel, loop: true do |channel, pid, payload| | |
yield channel | |
end | |
end | |
def channel | |
[self.class.table_name, id].join '_' | |
end | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'sinatra' | |
require 'json' | |
require_relative 'resource' | |
configure do | |
mime_type :event_stream, 'text/event-stream' | |
end | |
get '/:id/stream', provides: :event_stream do | |
stream do |out| | |
resource.listen do |channel| | |
out << message(event: channel, data: resource.reload) | |
break if out.closed? | |
end | |
end | |
end | |
def resource | |
@resource ||= Resource[params[:id]] | |
end | |
def message(event:, data:) | |
"event: %s\ndata: %s\\n" % [event, data.to_json] | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'securerandom' | |
require_relative 'resource' | |
loop do | |
Resource[2].update title: SecureRandom.hex | |
sleep 5 | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment