Last active
April 19, 2019 07:53
-
-
Save unplugandplay/f874e42c18088e747394726f0082d8b7 to your computer and use it in GitHub Desktop.
When amber and imba collid in harmony to generate server side event (SSE)
This file contains hidden or 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
-- imba part: | |
tag App | |
def build | |
messages | |
def messages | |
console.log('messages') | |
@last_event_id = "0" | |
@evtSource = EventSource.new "/messages/live?last_event_id={@last_event_id}" | |
@messages = [] | |
@evtSource:onmessage = do |e| | |
console.log(e) | |
let message = JSON.parse(e:data) | |
console.log(message) | |
@messages.push({name: message:name, content: message:content}) | |
Imba.commit | |
def render | |
<self> | |
<div.messages> | |
"Messages" | |
for message in @messages | |
<Message[message]> | |
Imba.mount <App> | |
-- amber part | |
class MessageController < ApplicationController | |
def live | |
response.headers["Content-Type"] = "text/event-stream" | |
messages = Message.all.last(10) # where params ... | |
last_event_id = params[:last_event_id] || "0" | |
my_json = messages[(last_event_id).to_i+1].to_json | |
"retry: 1000 | |
event: message | |
id: params[:id] | |
data: #{my_json} | |
" if my_json | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The challenge was to create simple a SSE using blazing fast (still underground) techs.
For the time being, Amber as no internal way to generate SSE in streaming way. This is just a gist, but a more sustainable way would be to only send new info as to block (put on wait) rendering in the live method, until there is new info to render, so even without pure streaming we are still taking advantage of the keep-alive persisting connecting