@message-queue-toolkit/core
Version:
Useful utilities, interfaces and base classes for message queue handling. Supports AMQP and SQS with a common abstraction on top currently
43 lines • 1.67 kB
JavaScript
const DEFAULT_SCHEMA_KEY = Symbol('NO_MESSAGE_TYPE');
export class MessageSchemaContainer {
messageDefinitions;
messageSchemas;
messageTypeField;
constructor(options) {
this.messageTypeField = options.messageTypeField;
this.messageSchemas = this.resolveMap(options.messageSchemas);
this.messageDefinitions = this.resolveMap(options.messageDefinitions ?? []);
}
resolveSchema(
// biome-ignore lint/suspicious/noExplicitAny: This is expected
message) {
const messageType = this.messageTypeField ? message[this.messageTypeField] : undefined;
const schema = this.messageSchemas[messageType ?? DEFAULT_SCHEMA_KEY];
if (!schema) {
return {
error: new Error(`Unsupported message type: ${messageType ?? DEFAULT_SCHEMA_KEY.toString()}`),
};
}
return { result: schema };
}
resolveMap(array) {
const result = {};
for (const item of array) {
let type;
if (this.messageTypeField) {
type =
'publisherSchema' in item
? // @ts-expect-error
item.publisherSchema?.shape[this.messageTypeField]?.value
: // @ts-expect-error
item.shape?.[this.messageTypeField]?.value;
}
const key = type ?? DEFAULT_SCHEMA_KEY;
if (result[key])
throw new Error(`Duplicate schema for type: ${key.toString()}`);
result[key] = item;
}
return result;
}
}
//# sourceMappingURL=MessageSchemaContainer.js.map