quintodrome/ui/src/eventStream.js

Ignoring revisions in .git-blame-ignore-revs. Click here to bypass and see the normal blame view.

62 lines
1.4 KiB
JavaScript
Raw Normal View History

import { baseUrl } from './utils'
import throttle from 'lodash.throttle'
2020-11-13 14:40:33 -09:00
import { processEvent, serverDown } from './actions'
let es = null
2020-11-13 14:40:33 -09:00
let dispatch = null
let timeout = null
const defaultIntervalCheck = 20000
const errorIntervalCheck = 2000
let currentIntervalCheck = defaultIntervalCheck
const getEventStream = () => {
if (es === null) {
es = new EventSource(
baseUrl(`/app/api/events?jwt=${localStorage.getItem('token')}`)
)
}
return es
}
// Reestablish the event stream after 20 secs of inactivity
2020-11-13 14:40:33 -09:00
const setTimeout = (value) => {
currentIntervalCheck = value
if (timeout != null) {
window.clearTimeout(timeout)
}
2020-11-13 14:40:33 -09:00
timeout = window.setTimeout(() => {
if (es != null) {
es.close()
}
es = null
2020-11-13 14:40:33 -09:00
startEventStream(dispatch)
}, currentIntervalCheck)
}
2020-11-13 14:40:33 -09:00
export const startEventStream = (dispatchFunc) => {
dispatch = dispatchFunc
setTimeout(currentIntervalCheck)
if (!localStorage.getItem('token')) {
console.log('Cannot create a unauthenticated EventSource')
return
}
const es = getEventStream()
es.onmessage = throttle(
(msg) => {
const data = JSON.parse(msg.data)
if (data.name !== 'keepAlive') {
2020-11-13 14:40:33 -09:00
dispatch(processEvent(data))
}
2020-11-13 14:40:33 -09:00
setTimeout(defaultIntervalCheck) // Reset timeout on every received message
},
100,
{ trailing: true }
)
2020-11-13 14:40:33 -09:00
es.onerror = (e) => {
setTimeout(errorIntervalCheck)
dispatch(serverDown())
}
return es
}