import { Response } from "express" ; const KEEP_ALIVE_INTERVAL = 5 * 1000 ; /**
 * Stream array of objects as JSON to client.
 */ export const sendChunkedJson = ( res ) => { let isFirstChunk = true ; res . header ( 'Content-Type' , 'application/json' ) ; res . header ( 'Transfer-Encoding' , 'chunked' ) ; const sendKeepAlive = ( ) => res . write ( '\r\n' ) ; const keepAliveInterval = setInterval ( sendKeepAlive , KEEP_ALIVE_INTERVAL ) ; return { push ( chunk ) { res . write ( isFirstChunk ? '[' : ',' ) ; res . write ( JSON . stringify ( chunk ) ) ; res . write ( '\r\n' ) ; isFirstChunk = false ; } , end ( ) { clearInterval ( keepAliveInterval ) ; if ( isFirstChunk ) { res . write ( '[' ) ; } res . end ( ']' ) ; } , fail ( code , message ) { clearInterval ( keepAliveInterval ) ; res . status ( code ) ; res . end ( message ) ; } } ; } ;