/** * Connects to Kafka and subscribes to each topic * * @returns a Promise that resolves if the connection is successful and rejects otherwise */ public async connect(): Promise<void> { await this.consumer.connect() for (const topic of this.topics) { await this.consumer.subscribe({ topic }) } this.isReady = true }
async function run() { await producer.connect(); await consumer.connect(); // receive certification service response await consumer.subscribe({ topic: 'certification-response' }); await consumer.run({ eachMessage: async ({ topic, partition, message }) => { console.log('Response', String(message.value)); }, }); app.listen(3333); }
const consumeProductStream = async (handler) => { await consumer.connect() await consumer.subscribe({ topic: 'products', fromBeginning: false }) await consumer.run({ eachMessage: async ({ topic, partition, message }) => { console.log('received message') try { await handler(JSON.parse(message.value.toString())) } catch (e) { console.error('unable to handle incoming message', e) } }, }) }
async function run() { await consumer.connect(); await consumer.subscribe({ topic }); await consumer.run({ eachMessage: async ({ topic, partition, message }) => { const prefix = `${topic}[${partition} | ${message.offset}] / ${message.timestamp}`; console.log(`- ${prefix} ${message.key}#${message.value}`); // send message for api const payload = JSON.parse(message.value); producer.send({ topic: 'certification-response', messages: [ { value: `User certificate ${payload.user.name} from course ${payload.course} is generated!`} ] }) } }) }
async function f1 () { await consumer.connect() await consumer.subscribe({ topic: 'jsapp1', }) await consumer.run({ eachMessage: async ({ topic, partition, message }) => { console.log({ value: message.value.toString(), }) }, }) // await consumer.disconnect() }