import Router from '../control/Router' ; import Manager from '../control/Manager' ; import State from '../State' ; import { parseEndpoint } from '../utility' ; /** Creates an ```express``` middleware function to handle requests for SSE subscriptions (simply GET requests with the appropriate headers set).
 */ const sse = ( router , callback ) : Function => { return async ( req , res , next ) => { if ( req . get ( 'Accept' ) !== 'text/event-stream' ) { return next ( ) ; } const { method } = parseEndpoint ( req . method ) ; if ( method !== 'get' ) { return res . status ( 400 ) . send ( 'Invalid Method' ) ; } const headers = { 'Content-Type' : 'text/event-stream' , 'Cache-Control' : 'no-cache' , Connection : 'keep-alive' , } ; res . set ( headers ) . status ( 200 ) ; const client = ( path , state , render = true ) => { const _req = { } ; const _res = { locals : state , stream : ( data ) => res . write ( `data: ${ JSON . stringify ( render ? data . render ( ) : data ) }\n\n` ) , } ; callback ( _req , _res ) ; } ; const endpoint = `${ req . method } ${ req . path }` ; const args = { ... req . cookies , ... req . query , ... req . body , ... req . params } ; const state = await router . request ( 'get' , req . path , args ) ; Manager . access ( ) . subscribe ( client , state . $query ) ; return client ( endpoint , state , false ) ; } ; } ; export default sse ;