Integrating Server Sent Events with Vuex
Updating your front-end with Server Sent Events (henceforth ‘SSE’) has never been easier, simpler and cleaner.
Updating your application state in the background as of 2019 should be only done by SSE (or WebSockets — if you really need to utilise full-duplex communication). Specification and implementation — wise, SSEs are just text/event-stream Content Types, with a chunked Transfer Encoding.
All you need to do in order to start using this technology in your App is:
- Subscribe to an
EventSource
endpoint - Register Event Listeners or
handlers
- Have each handler parse the event and commit mutations or actions on your
vuex store
, effectively updating the state, thus any active/observing component
Subscribing and Routing Events
The SSE API is pretty easy to use. Here is my preferred structure for declaring handlers. Notice that the events are distributed to the handlers based on their eventType
. You could also route them based on their id
, or event content-wise, but I am sure it would not make sense in 99% of the cases.
We’re going to take MDN’s example a step further. eventsource
contains all the necessary files for this. eventsource/index.js
exposes only one function/entry point, which is the initial setup of the connection. Inside this function, eventsource/handlers
are registered. handlers/index.js
contains the manifest of all the handlers in use.
In this specific example from UAVCAN/Yukon, the client only has got one handler, the nodeStatus
one, which is used to update a specific node’s state, on said request:
handlers/index.js
is actually only a regular module index, exposing all the available handlers:
Updating State
You’ve already taken a glimpse of what the current structure looks like. Now that we can register handlers and parse event.data
(remember, it is a text stream
), it is time to mutate state. You can only do this properly by using one of two ways: actions
or mutations
. I used a Vuex mutation in this example, but you are free to use either of the two.
Testing
The reason that these snippets are designed with such structure is easy testing. Your components only rely on the Vuex State. Your state is only changed through actions and mutations. Your SSE only summons actions and mutations.
It is, therefore, easy to test:
- Assuming that you have already got your mutations and actions fully test covered
- You only have to write tests by providing a mock initial state, event data — asserting that correct changes were made
Thank you very much for your time, I hope you enjoyed reading this article as much I enjoyed writing and learning from it.