|
| 1 | +"use strict"; |
| 2 | + |
| 3 | +const { KafkaStreams } = require("./../index.js"); |
| 4 | +const { nativeConfig: config } = require("./../test/test-config.js"); |
| 5 | + |
| 6 | +const kafkaStreams = new KafkaStreams(config); |
| 7 | + |
| 8 | +kafkaStreams.on("error", (error) => { |
| 9 | + console.log("Error occured:", error.message); |
| 10 | +}); |
| 11 | + |
| 12 | +const stream = kafkaStreams.getKStream(null); |
| 13 | +//creating a stream without topic is possible |
| 14 | +//no consumer will be created during stream.start() |
| 15 | + |
| 16 | +// 2nd arg is the output partition count, if you do not provide a partition the messages are automatically split across based on key or randomly |
| 17 | +// 3nd arg is the produce type of the sinek library, suggestion: stick to "send" this leaves all design options for you |
| 18 | +stream |
| 19 | + .tap(console.log) // lets log some stream events |
| 20 | + .to("default-target-topic", 1, "send"); |
| 21 | +//define a topic to stream messages to, if nothing is actually defined in the kv structure |
| 22 | + |
| 23 | +//start the stream |
| 24 | +//(wait for the kafka producer to be ready, same as await .to()) |
| 25 | +//and write a few messages to the topic stream.start() |
| 26 | +stream.start().then((_) => { |
| 27 | + |
| 28 | + stream.writeToStream(getKafkaStyledMessage({ ping: "pong" })); // will be produced to default-target-topic |
| 29 | + stream.writeToStream(getKafkaStyledMessage({ ping: "pong" }, "other-topic")); // will be produced to other-topic |
| 30 | + stream.writeToStream([ |
| 31 | + getKafkaStyledMessage({ ping: "pong" }, "other-topic-2"), |
| 32 | + getKafkaStyledMessage({ ping: "pong" }, "other-topic-3") |
| 33 | + ]); |
| 34 | + |
| 35 | + //wait a few ms and close all connections |
| 36 | + setTimeout(kafkaStreams.closeAll.bind(kafkaStreams), 5000); |
| 37 | +}); |
| 38 | + |
| 39 | +// its very important the events on your stream are shipped in a certain format |
| 40 | +// if they are not in the required KV format they will be treated as message values and not as full kafka messages |
| 41 | +function getKafkaStyledMessage(payload, topic = undefined, partition = undefined) { |
| 42 | + return { |
| 43 | + key: null, // (required) just to not be undefined, keys will otherwise receive random uuids |
| 44 | + value: JSON.stringify(payload), // required, ensure this is a string or a buffer! |
| 45 | + // optional: |
| 46 | + topic, |
| 47 | + partition, |
| 48 | + }; |
| 49 | +} |
0 commit comments