Adding a communication channel between server and clients using SSE

This commit is contained in:
Deluan
2020-11-08 00:06:48 -05:00
parent 3fc81638c7
commit 2b1a5f579a
15 changed files with 395 additions and 25 deletions
+30
View File
@@ -0,0 +1,30 @@
import baseUrl from './utils/baseUrl'
import throttle from 'lodash.throttle'
// TODO https://stackoverflow.com/a/20060461
let es = null
let dispatchFunc = null
const getEventStream = () => {
if (es === null) {
es = new EventSource(
baseUrl(`/app/api/events?jwt=${localStorage.getItem('token')}`)
)
}
return es
}
export const startEventStream = (func) => {
const es = getEventStream()
dispatchFunc = func
es.onmessage = throttle(
(msg) => {
const data = JSON.parse(msg.data)
if (data.name !== 'keepAlive') {
dispatchFunc(data)
}
},
100,
{ trailing: true }
)
}