A lightweight, fully spec-compliant parser for the event stream format.
It only deals with the parsing of events and not any of the client/transport aspects. This is not a Server-sent Events (SSE) client.
Under the hood, it's a stateful parser that receives chunks (that are received from an HTTP client, for example) and emits events as it parses them. But it remembers the last event id and reconnection time and keeps emitting them as long as they are not overwritten by new ones.
BOM stripping is left as a responsibility of the chunk provider.
Add this line to your application's Gemfile:
gem 'event_stream_parser'
And then execute:
bundle
Or install it yourself as:
gem install event_stream_parser
Create a new Parser:
parser = EventStreamParser::Parser.new
Then, feed it chunks as they come in:
do_something_that_yields_chunks do |chunk|
parser.feed(chunk) do |type, data, id, reconnection_time|
puts "Event type: #{type}"
puts "Event data: #{data}"
puts "Event id: #{id}"
puts "Reconnection time: #{reconnection_time}"
end
end
Or use the stream
method to generate a proc that you can pass to a chunk
producer:
parser_stream = parser.stream do |type, data, id, reconnection_time|
puts "Event type: #{type}"
puts "Event data: #{data}"
puts "Event id: #{id}"
puts "Reconnection time: #{reconnection_time}"
end
do_something_that_yields_chunks(&parser_stream)
After checking out the repo:
- Run
bundle
to install dependencies. - Run
rake test
to run the tests. - Run
rubocop
to run Rubocop.
To install this gem onto your local machine, run bundle exec rake install
.
Bug reports and pull requests are welcome on GitHub at https://github.com/Shopify/event_stream_parser. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the Contributor Covenant code of conduct. Read more about contributing here.
The gem is available as open source under the terms of the MIT License.
Everyone interacting in this repository is expected to follow the Code of Conduct.