UNPKG

schematic-kafka

Version:

Encode and decode kafka messages with Confluent Schema Registry (pure typescript implementation)

37 lines 1.38 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.kafkaDecode = exports.kafkaEncode = void 0; /** * Prefix kafka message with the correct preamble for the given schema id * @param {Buffer} encodedMessage already encoded message * @param {number} schemaId * @returns {Buffer} */ const kafkaEncode = (schemaId, encodedMessage) => { if (!(encodedMessage instanceof Buffer)) { throw new Error("encoded message must be of type Buffer"); } // Allocate buffer for encoded kafka event (1 byte preable + 4 byte messageid + sizeof(encodedMessage)) const message = Buffer.alloc(encodedMessage.length + 5); message.writeUInt8(0); message.writeUInt32BE(schemaId, 1); encodedMessage.copy(message, 5); return message; }; exports.kafkaEncode = kafkaEncode; /** * Decode the schema preamble and return schemaId anf payload * @param {Buffer} rawMessage Unencoded message from kafka event * @returns schemaId and unencoded payload */ const kafkaDecode = (rawMessage) => { if (rawMessage.readUInt8(0) !== 0) { // throw new Error(`Missing schema preamble.`) return { payload: rawMessage }; } const schemaId = rawMessage.readUInt32BE(1); const payload = rawMessage.slice(5); return { schemaId, payload }; }; exports.kafkaDecode = kafkaDecode; //# sourceMappingURL=kafka-helper.js.map