quintodrome/ui/src/eventStream.js

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

51 lines
1.5 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'
import { REST_URL } from './consts'
2023-05-17 07:22:36 -08:00
const newEventStream = async () => {
let url = baseUrl(`${REST_URL}/events`)
if (localStorage.getItem('token')) {
url = url + `?jwt=${localStorage.getItem('token')}`
}
2023-05-17 07:22:36 -08:00
return new EventSource(url)
2021-11-29 14:49:29 -09:00
}
2023-05-17 07:22:36 -08:00
const eventHandler = (dispatchFn) => (event) => {
const data = JSON.parse(event.data)
if (event.type !== 'keepAlive') {
2023-05-17 07:22:36 -08:00
dispatchFn(processEvent(event.type, data))
}
}
2023-05-17 07:22:36 -08:00
const throttledEventHandler = (dispatchFn) =>
throttle(eventHandler(dispatchFn), 100, { trailing: true })
2023-05-17 07:22:36 -08:00
const startEventStream = async (dispatchFn) => {
if (!localStorage.getItem('is-authenticated')) {
2021-11-29 14:49:29 -09:00
return Promise.resolve()
}
2023-05-17 07:22:36 -08:00
return newEventStream()
.then((newStream) => {
2023-05-17 07:22:36 -08:00
newStream.addEventListener('serverStart', eventHandler(dispatchFn))
newStream.addEventListener(
'scanStatus',
throttledEventHandler(dispatchFn),
2023-05-17 07:22:36 -08:00
)
newStream.addEventListener('refreshResource', eventHandler(dispatchFn))
newStream.addEventListener('keepAlive', eventHandler(dispatchFn))
newStream.onerror = (e) => {
// eslint-disable-next-line no-console
console.log('EventStream error', e)
2023-05-17 07:22:36 -08:00
dispatchFn(serverDown())
}
return newStream
})
.catch((e) => {
// eslint-disable-next-line no-console
console.log(`Error connecting to server:`, e)
})
}
2023-05-17 07:22:36 -08:00
export { startEventStream }