All files / lib/libs/api kafka.ts

100% Statements 15/15
87.5% Branches 7/8
100% Functions 2/2
100% Lines 15/15

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55      3x                           3x 2x       3x 3x   3x           3x         3x 3x         2x 1x     1x   1x   2x 2x      
import { Kafka, Message, Producer } from "kafkajs";
import { validateEnvVariable } from "shared-utils";
 
const kafka = new Kafka({
  clientId: "submit",
  brokers: process.env.brokerString ? process.env.brokerString.split(",") : [],
  retry: {
    initialRetryTime: 300,
    retries: 8,
  },
  ssl: {
    rejectUnauthorized: false,
  },
});
 
let producer: Producer;
export function getProducer() {
  validateEnvVariable("brokerString");
  return kafka.producer();
}
 
export async function produceMessage(topic: string, key: string, value: string) {
  producer = producer || getProducer();
  await producer.connect();
 
  const message: Message = {
    key: key,
    value: value,
    partition: 0,
    headers: { source: "mako" },
  };
  console.log(
    "About to send the following message to kafka\n" +
      JSON.stringify({ ...message, value: JSON.parse(message.value as string) }, null, 2),
  );
 
  try {
    const result = await producer.send({
      topic,
      messages: [message],
    });
 
    if (!result || result.length === 0) {
      throw new Error("Kafka did not return a valid response.");
    }
 
    console.log("Message sent successfully", result);
 
    return result;
  } catch (error) {
    console.error("Error sending message:", error);
    throw error;
  }
}