umami/lib/kafka.js

75 lines
1.5 KiB
JavaScript
Raw Normal View History

2022-08-25 20:07:47 +02:00
import { Kafka, logLevel } from 'kafkajs';
2022-08-12 18:21:43 +02:00
import dateFormat from 'dateformat';
2022-08-26 07:04:32 +02:00
export function getClient() {
2022-08-12 18:21:43 +02:00
if (!process.env.KAFKA_URL) {
return null;
}
const url = new URL(process.env.KAFKA_URL);
const brokers = process.env.KAFKA_BROKER.split(',');
if (url.username.length === 0 && url.password.length === 0) {
return new Kafka({
clientId: 'umami',
brokers: brokers,
2022-08-18 20:07:30 +02:00
connectionTimeout: 3000,
2022-08-25 20:07:47 +02:00
logLevel: logLevel.ERROR,
2022-08-12 18:21:43 +02:00
});
} else {
return new Kafka({
clientId: 'umami',
brokers: brokers,
2022-08-18 20:07:30 +02:00
connectionTimeout: 3000,
2022-08-12 18:21:43 +02:00
ssl: true,
sasl: {
mechanism: 'plain',
username: url.username,
password: url.password,
},
});
}
}
2022-08-26 07:04:32 +02:00
const kafka = global.kafka || getClient();
2022-08-25 20:07:47 +02:00
let kafkaProducer = null;
2022-08-12 18:21:43 +02:00
2022-08-25 20:07:47 +02:00
(async () => {
2022-08-26 07:04:32 +02:00
kafkaProducer = global.kakfaProducer || (await getProducer());
2022-08-25 20:07:47 +02:00
if (process.env.NODE_ENV !== 'production') {
global.kafka = kafka;
global.kakfaProducer = kafkaProducer;
}
})();
2022-08-12 18:21:43 +02:00
2022-08-25 20:07:47 +02:00
export { kafka, kafkaProducer };
2022-08-12 18:21:43 +02:00
2022-08-26 07:43:22 +02:00
async function getProducer() {
2022-08-12 18:21:43 +02:00
const producer = kafka.producer();
await producer.connect();
2022-08-25 20:07:47 +02:00
return producer;
}
2022-08-26 07:43:22 +02:00
function getDateFormat(date) {
2022-08-26 07:04:32 +02:00
return dateFormat(date, 'UTC:yyyy-mm-dd HH:MM:ss');
}
2022-08-26 07:43:22 +02:00
async function sendMessage(params, topic) {
2022-08-25 20:07:47 +02:00
await kafkaProducer.send({
2022-08-12 18:21:43 +02:00
topic,
messages: [
{
key: 'key',
value: JSON.stringify(params),
},
],
2022-08-25 20:07:47 +02:00
acks: 0,
2022-08-12 18:21:43 +02:00
});
}
2022-08-26 07:43:22 +02:00
export default {
getDateFormat,
sendMessage,
};