@electric-sql/d2ts
Version:
D2TS is a TypeScript implementation of Differential Dataflow.
50 lines • 1.97 kB
JavaScript
import { MessageType, } from '../types.js';
import { DifferenceStreamWriter, UnaryOperator, } from '../graph.js';
import { StreamBuilder } from '../d2.js';
/**
* Operator that outputs the messages in the stream
*/
export class OutputOperator extends UnaryOperator {
#fn;
constructor(id, inputA, output, fn, initialFrontier) {
super(id, inputA, output, initialFrontier);
this.#fn = fn;
}
run() {
for (const message of this.inputMessages()) {
this.#fn(message);
if (message.type === MessageType.DATA) {
const { version, collection } = message.data;
this.output.sendData(version, collection);
}
else if (message.type === MessageType.FRONTIER) {
const frontier = message.data;
if (!this.inputFrontier().lessEqual(frontier)) {
throw new Error('Invalid frontier update');
}
this.setInputFrontier(frontier);
if (!this.outputFrontier.lessEqual(this.inputFrontier())) {
throw new Error('Invalid frontier state');
}
if (this.outputFrontier.lessThan(this.inputFrontier())) {
this.outputFrontier = this.inputFrontier();
this.output.sendFrontier(this.outputFrontier);
}
}
}
}
}
/**
* Outputs the messages in the stream
* @param fn - The function to call with each message
*/
export function output(fn) {
return (stream) => {
const output = new StreamBuilder(stream.graph, new DifferenceStreamWriter());
const operator = new OutputOperator(stream.graph.getNextOperatorId(), stream.connectReader(), output.writer, fn, stream.graph.frontier());
stream.graph.addOperator(operator);
stream.graph.addStream(output.connectReader());
return output;
};
}
//# sourceMappingURL=output.js.map