kafka-pub-sub
Version:
Enterprise-grade Kafka publish/subscribe library for Node.js — producer pool, batch sending, DLQ, SSL/SASL, multi-broker, and real-world industry examples.
34 lines (28 loc) • 1.05 kB
JavaScript
const Joi = require('joi');
// Kafka's official topic naming rule: alphanumeric, dot, dash, underscore; max 249 chars
const TOPIC_REGEX = /^[a-zA-Z0-9._-]+$/;
/**
* Validates a Kafka topic name against Kafka's official naming rules.
*
* Rules:
* - Must be a non-empty string
* - 1–249 characters (Kafka broker hard limit)
* - Only alphanumeric characters, dots (.), hyphens (-), and underscores (_)
*
* @param {string} topic - The topic name to validate.
* @throws {Error} When the topic is invalid.
*/
const validateTopic = (topic) => {
const schema = Joi.object()
.keys({
topic: Joi.string().min(1).max(249).pattern(TOPIC_REGEX).required().description('Kafka topic name'),
})
.unknown();
const { error } = schema.prefs({ errors: { label: 'key' } }).validate({ topic });
if (error) {
throw new Error(
'Invalid topic: must be a non-empty string up to 249 characters containing only alphanumeric characters, dots (.), hyphens (-), or underscores (_)',
);
}
};
module.exports = validateTopic;