@glowlabs-org/events-sdk
Version:
Typed event SDK for Glow, powered by RabbitMQ and Zod.
58 lines (57 loc) • 2.44 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.validateZoneNameAndId = validateZoneNameAndId;
exports.validateEventPayload = validateEventPayload;
exports.processEventMessage = processEventMessage;
exports.validateName = validateName;
exports.buildAmqpUrl = buildAmqpUrl;
const event_registry_1 = require("./event-registry");
const zones_1 = require("./zones");
const patterns_1 = require("./patterns");
/**
* Validates that the zoneName matches the zoneId using the zoneMap.
* Throws an error if the values are inconsistent.
*/
function validateZoneNameAndId(zoneId, zoneName) {
if (typeof zoneId === "number" &&
zoneId in zones_1.zoneMap &&
zoneName !== zones_1.zoneMap[zoneId]) {
throw new Error(`zoneName '${zoneName}' does not match zoneId '${zoneId}' (expected '${zones_1.zoneMap[zoneId]}')`);
}
}
/**
* Validates the event payload against the schema for the given eventType and schemaVersion.
* Throws an error if the schema does not exist or the payload is invalid.
*/
function validateEventPayload(eventType, schemaVersion, payload) {
const schema = (0, event_registry_1.getEventSchema)(eventType, schemaVersion);
if (!schema)
throw new Error(`No schema for event: ${eventType} ${schemaVersion}`);
try {
schema.parse(payload);
}
catch (err) {
throw new Error(`Payload does not match schema for event: ${eventType} ${schemaVersion}: ${err.message}`);
}
}
/**
* Processes a message object as the listener would, validating zone and schema.
* Throws if validation fails, returns the parsed event otherwise.
*/
function processEventMessage(msg) {
const decoded = JSON.parse(msg.content.toString());
const [eventType, versionStr] = msg.fields.routingKey.split(".v");
const schemaVersion = `v${versionStr}`;
validateZoneNameAndId(decoded.zoneId, decoded.zoneName);
validateEventPayload(eventType, schemaVersion, decoded);
return (0, event_registry_1.getEventSchema)(eventType, schemaVersion).parse(decoded);
}
function validateName(name, type) {
if (!patterns_1.exchangeOrQueueNamePattern.test(name)) {
throw new Error(`${type} name '${name}' is invalid. Must be dot-separated (e.g., 'glow.zone-1.events').`);
}
}
function buildAmqpUrl({ username, password, host, }) {
const url = new URL(`amqp://${username}:${password}@${host}`);
return url.toString();
}