Skip to content
Source
Sign inSign up
TanStack/db
Open History to see the last commit

output.ts

52 lines1.3 KB

1import { DifferenceStreamWriter, UnaryOperator } from "../graph.js"
2import { StreamBuilder } from "../d2.js"
3import type { IStreamBuilder, PipedOperator } from "../types.js"
4import type { DifferenceStreamReader } from "../graph.js"
5import type { MultiSet } from "../multiset.js"
6​
7/**
8 * Operator that outputs the messages in the stream
9 */
10export class OutputOperator<T> extends UnaryOperator<T> {
11 #fn: (data: MultiSet<T>) => void
12​
13 constructor(
14 id: number,
15 inputA: DifferenceStreamReader<T>,
16 outputWriter: DifferenceStreamWriter<T>,
17 fn: (data: MultiSet<T>) => void
18 ) {
19 super(id, inputA, outputWriter)
20 this.#fn = fn
21 }
22​
23 run(): void {
24 for (const message of this.inputMessages()) {
25 this.#fn(message)
26 this.output.sendData(message)
27 }
28 }
30​
31/**
32 * Outputs the messages in the stream
33 * @param fn - The function to call with each message
34 */
35export function output<T>(
36 fn: (data: MultiSet<T>) => void
37): PipedOperator<T, T> {
38 return (stream: IStreamBuilder<T>): IStreamBuilder<T> => {
39 const outputStream = new StreamBuilder<T>(
40 stream.graph,
41 new DifferenceStreamWriter<T>()
42 )
43 const operator = new OutputOperator<T>(
44 stream.graph.getNextOperatorId(),
45 stream.connectReader(),
46 outputStream.writer,
47 fn
48 )
49 stream.graph.addOperator(operator)
50 return outputStream
51 }