@mdf.js/openc2
Version:
MMS - API - Observability
82 lines • 3.21 kB
JavaScript
;
/**
* Copyright 2024 Mytra Control S.L. All rights reserved.
*
* Use of this source code is governed by an MIT-style license that can be found in the LICENSE file
* or at https://opensource.org/licenses/MIT.
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.RedisConsumerAdapter = void 0;
const crash_1 = require("@mdf.js/crash");
const RedisAdapter_1 = require("./RedisAdapter");
class RedisConsumerAdapter extends RedisAdapter_1.RedisAdapter {
/**
* Create a new OpenC2 adapter for Redis
* @param adapterOptions - Adapter configuration options
* @param redisOptions - Redis configuration options
*/
constructor(adapterOptions, redisOptions) {
super(adapterOptions, 'consumer', redisOptions);
/** Wrapper function for message adaptation */
this.subscriptionAdapter = (pattern, topic, incomingMessage) => {
if (this.handler) {
try {
const parsedMessage = JSON.parse(incomingMessage);
const onDone = async (error, message) => {
if (!error && message) {
await this.publish(message);
}
else if (error) {
this.onErrorHandler(error);
}
};
this.handler(parsedMessage, onDone);
}
catch (rawError) {
const error = crash_1.Crash.from(rawError);
this.onErrorHandler(new crash_1.Crash(`Error performing the adaptation of the incoming message: ${error.message}`, error.uuid, { cause: error }));
}
}
};
}
/**
* Subscribe the incoming message handler to the underlayer transport system
* @param handler - handler to be used
* @returns
*/
async subscribe(handler) {
this.handler = handler;
this.subscriber.client.on('pmessage', this.subscriptionAdapter);
}
/**
* Unsubscribe the incoming message handler from the underlayer transport system
* @param handler - handler to be used
* @returns
*/
async unsubscribe(handler) {
this.handler = undefined;
this.subscriber.client.off('pmessage', this.subscriptionAdapter);
}
/**
* Perform the publication of the message in the underlayer transport system
* @param message - message to be published
* @returns
*/
async publish(message) {
try {
const topics = this.defineTopics(message);
const parsedMessage = JSON.stringify(message);
for (const topic of topics) {
await this.publisher.client.publish(topic, parsedMessage);
}
}
catch (rawError) {
const error = crash_1.Crash.from(rawError);
this.onErrorHandler(new crash_1.Crash(`Error performing the publication of the message: ${error.message}`, error.uuid, {
cause: error,
}));
}
}
}
exports.RedisConsumerAdapter = RedisConsumerAdapter;
//# sourceMappingURL=RedisConsumerAdapter.js.map