( res: http.ServerResponse, chunks: object[], options?: NDJSONStreamOptions, )
| 19 | } |
| 20 | |
| 21 | export async function writeNDJSONStream( |
| 22 | res: http.ServerResponse, |
| 23 | chunks: object[], |
| 24 | options?: NDJSONStreamOptions, |
| 25 | ): Promise<boolean> { |
| 26 | const opts = options ?? {}; |
| 27 | const latency = opts.latency ?? 0; |
| 28 | const profile = opts.streamingProfile; |
| 29 | const { recordedTimings, replaySpeed } = opts; |
| 30 | const signal = opts.signal; |
| 31 | const onChunkSent = opts.onChunkSent; |
| 32 | |
| 33 | if (res.writableEnded) return true; |
| 34 | res.setHeader("Content-Type", "application/x-ndjson"); |
| 35 | res.setHeader("Cache-Control", "no-cache"); |
| 36 | res.setHeader("Connection", "keep-alive"); |
| 37 | |
| 38 | let chunkIndex = 0; |
| 39 | for (const chunk of chunks) { |
| 40 | const chunkDelay = calculateDelay(chunkIndex, profile, latency, recordedTimings, replaySpeed); |
| 41 | if (chunkDelay > 0) { |
| 42 | await delay(chunkDelay, signal); |
| 43 | } |
| 44 | if (signal?.aborted) return false; |
| 45 | if (res.writableEnded) return true; |
| 46 | res.write(JSON.stringify(chunk) + "\n"); |
| 47 | onChunkSent?.(); |
| 48 | if (signal?.aborted) return false; |
| 49 | chunkIndex++; |
| 50 | } |
| 51 | |
| 52 | if (!res.writableEnded) { |
| 53 | res.end(); |
| 54 | } |
| 55 | return true; |
| 56 | } |
no test coverage detected
searching dependent graphs…