import { Job , } from './jobTypes' ; export type JobSubscription = ( jobState : any ) => void ; export type RemoveSubscription = ( ) => void ; type JobSubscriptionNotification = { jobState : 'JOB_STARTED' | 'JOB_DONE' | 'JOB_NOT_FOUND' | 'JOB_INTERMEDIATE' | 'JOB_FAILED' ; value ? : any ; } ; export function JobSubscriptions ( ) { const topics = { } ; const subscriptions = { } ; function addTopic ( topic , job ) { topics [ topic ] = job ; } function addSubscription ( topic , subscription ) { if ( subscriptions [ topic ] ) { subscriptions [ topic ] . add ( subscription ) ; } else { subscriptions [ topic ] = new Set ( [ subscription ] ) ; } const job = topics [ topic ] ; if ( job ) { if ( job . state ) { subscription ( { jobState : 'JOB_INTERMEDIATE' , value : job . state } ) ; } else { subscription ( { jobState : 'JOB_STARTED' } ) ; } } else { subscription ( { jobState : 'JOB_NOT_FOUND' } ) ; } return ( ) => subscriptions [ topic ] && subscriptions [ topic ] . delete ( subscription ) ; } function notifySubscriptions ( topic , notification ) { subscriptions [ topic ] . forEach ( subscription => subscription ( notification ) ) ; } function removeTopic ( topic ) { delete subscriptions [ topic ] ; delete topics [ topic ] ; } return { addSubscription , notifySubscriptions , removeTopic , addTopic , } ; }