@vpriem/kafka-broker
Version:
Easily compose and manage your kafka resources in one place
42 lines • 1.6 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.encodeMessagesWithRegistry = void 0;
const types_1 = require("./types");
const BrokerError_1 = require("./BrokerError");
const subjectToId = {};
// TODO: build cache with TTL or fix @kafkajs/confluent-schema-registry
const getSchemaIdFromSubject = async (schemaRegistry, { subject, version }) => {
const hash = `${subject}:${version}`;
if (!subjectToId[hash]) {
subjectToId[hash] = await (version === 'latest'
? schemaRegistry.getLatestSchemaId(subject)
: schemaRegistry.getRegistryId(subject, version));
}
return subjectToId[hash];
};
const isSchemaSubject = (schema) => typeof schema.subject !== 'undefined';
const encodeMessagesWithRegistry = async (messages, schema, schemaRegistry) => {
if (typeof schemaRegistry === 'undefined') {
throw new BrokerError_1.BrokerError('Registry not found');
}
let schemaId;
if (isSchemaSubject(schema)) {
schemaId = await getSchemaIdFromSubject(schemaRegistry, schema);
}
else {
schemaId = schema.id;
}
return Promise.all(messages.map(async (message) => {
const value = await schemaRegistry.encode(schemaId, message.value);
return {
...message,
value,
headers: {
...message.headers,
'content-type': types_1.ContentTypes.SCHEMA_REGISTRY,
},
};
}));
};
exports.encodeMessagesWithRegistry = encodeMessagesWithRegistry;
//# sourceMappingURL=encodeMessagesWithRegistry.js.map