This class can help you parse a single server sent event or a stream of them.
You can inherit the class for a custom application.
The parse_sse()
function wraps this class for a more functional approach.
Details
The HTML specification
tells us that event streams are composed by chunks (also called blocks, or messages) and lines.
A single new line character (\n
) states the end of a line, and two consecutive new line characters (\n\n
) state the end of a chunk.
This means that, in practice, an event can be composed of one or more chunks, and a chunk can be composed of one or more lines.
: This is the first chunk, it has one line
data
: This is the second chunk
data: It has two lines
extra
: This is the third chunk, it has an id field. This is common.
data: 123
id
: Lines that start with a colon are comments, they will be ignored
: This is the forth chunk, it has a comment
data
: This is the fifth chunk. Normally you will receive a data field
data: But the server can send custom field names. SSEparser parses them too.
custom
Typically, an event stream will send a single chunk for event, but it is important
to understand that event != chunk because SSEparser$events
will be a list of
all the chunks received as it makes a more consistent output.
Public fields
events
List that contains all the events parsed. When the class is initialized, is just an empty list.
Methods
Method append_parsed_sse()
Takes a parsed event and appends it to the events
field. You can overwrite this method if you decide to extend this class.
Method parse_sse()
Takes a string that comes from a server sent event and parses it to an R list. You should never overwrite this method.
Arguments
event
A length 1 string containing a server sent event as specified in the HTML spec.
Examples
example_event <-
"data: This is the first chunk, it has one line
data: This is the second chunk
extra: It has two lines
data: This is the third chunk, it has an id field. This is common.
id: 123
: Lines that start with a colon are comments, they will be ignored
data: This is the fourth chunk, it has a comment
data: This is the fifth chunk. Normally you will receive a data field
custom: But the server can send custom field names. SSEparser parses them too."
parser <- SSEparser$new()
parser$parse_sse(example_event)
str(parser$events)
#> List of 5
#> $ :List of 1
#> ..$ data: chr "This is the first chunk, it has one line"
#> $ :List of 2
#> ..$ data : chr "This is the second chunk"
#> ..$ extra: chr "It has two lines"
#> $ :List of 2
#> ..$ data: chr "This is the third chunk, it has an id field. This is common."
#> ..$ id : chr "123"
#> $ :List of 1
#> ..$ data: chr "This is the fourth chunk, it has a comment"
#> $ :List of 2
#> ..$ data : chr "This is the fifth chunk. Normally you will receive a data field"
#> ..$ custom: chr "But the server can send custom field names. SSEparser parses them too."