Pinafore-Web-Client-Frontend/routes/_actions/streaming.js

46 lines
1.5 KiB
JavaScript
Raw Normal View History

2018-02-11 22:46:57 +01:00
import { TimelineStream } from '../_api/TimelineStream'
import { scheduleIdleTask } from '../_utils/scheduleIdleTask'
import { mark, stop } from '../_utils/marks'
2018-02-17 04:38:21 +01:00
import { deleteStatus } from './deleteStatuses'
import { addStatusOrNotification } from './addStatusOrNotification'
2018-02-15 18:02:46 +01:00
function processMessage (instanceName, timelineName, message) {
mark('processMessage')
2018-02-11 22:46:57 +01:00
let { event, payload } = message
2018-02-15 18:02:46 +01:00
switch (event) {
case 'delete':
2018-03-11 01:21:10 +01:00
deleteStatus(instanceName, payload)
2018-02-15 18:02:46 +01:00
break
case 'update':
2018-03-11 01:21:10 +01:00
addStatusOrNotification(instanceName, timelineName, JSON.parse(payload))
2018-02-15 18:02:46 +01:00
break
case 'notification':
2018-03-11 01:21:10 +01:00
addStatusOrNotification(instanceName, 'notifications', JSON.parse(payload))
2018-02-15 18:02:46 +01:00
break
}
stop('processMessage')
2018-02-11 22:46:57 +01:00
}
export function createStream (streamingApi, instanceName, accessToken, timelineName) {
2018-02-11 23:11:03 +01:00
return new TimelineStream(streamingApi, accessToken, timelineName, {
onMessage (msg) {
2018-02-15 18:02:46 +01:00
if (msg.event !== 'update' && msg.event !== 'delete' && msg.event !== 'notification') {
2018-02-11 22:46:57 +01:00
console.error("don't know how to handle event", msg)
return
}
scheduleIdleTask(() => {
2018-02-15 18:02:46 +01:00
processMessage(instanceName, timelineName, msg)
2018-02-11 22:46:57 +01:00
})
},
2018-02-11 23:11:03 +01:00
onOpen () {
2018-02-11 22:46:57 +01:00
console.log('opened stream for timeline', timelineName)
},
2018-02-11 23:11:03 +01:00
onClose () {
2018-02-11 22:46:57 +01:00
console.log('closed stream for timeline', timelineName)
},
2018-02-11 23:11:03 +01:00
onReconnect () {
2018-02-11 22:46:57 +01:00
console.log('reconnected stream for timeline', timelineName)
}
})
2018-02-14 04:35:46 +01:00
}