import { Injectable, Logger, OnModuleDestroy, OnModuleInit, } from "@nestjs/common"; import { AgentService } from "../asker/agent.service"; import { ConsumerService } from "@ocm-engine/nats"; import { ConfigService } from "@nestjs/config"; import { IConfAgent } from "@ocm-engine/config"; import { GatewayClient } from "@ocm-engine/clients"; import { CONNECTION_ACCEPT, CONNECTION_CREATE, CONNECTION_GET, CONNECTION_LIST, CreateInvitationResponseDto, GetConnectionRequestDto, } from "@ocm-engine/dtos"; @Injectable() export class AgentConsumerService implements OnModuleInit, OnModuleDestroy { private readonly logger = new Logger(AgentConsumerService.name); constructor( private readonly agentService: AgentService, private readonly consumerService: ConsumerService, private readonly configService: ConfigService, private readonly gatewayClient: GatewayClient, ) {} async onModuleInit(): Promise<void> { const config = this.configService.get<IConfAgent>("agent"); if (config?.agentIsRest) { this.logger.log( "Agent is configured as rest, there is no need for consumer!", ); return; } await this.consumerService.subscribe(async (event) => { this.logger.debug(JSON.stringify(event, null, 2)); let data; switch (event.type) { case CONNECTION_CREATE: data = await this.agentService.createInvitation(); break; case CONNECTION_ACCEPT: // eslint-disable-next-line no-case-declarations const c = event.data as CreateInvitationResponseDto; data = await this.agentService.acceptInvitation(c.invitationUrl); break; case CONNECTION_LIST: data = await this.agentService.fetchConnections(); break; case CONNECTION_GET: // eslint-disable-next-line no-case-declarations const g = event.data as GetConnectionRequestDto; data = await this.agentService.getConnectionById(g.connectionId); } event.data = data; this.logger.debug(`before sending ${JSON.stringify(event, null, 2)}`); this.gatewayClient.sendPayload(event); return; }); } async onModuleDestroy(): Promise<void> { this.logger.log("disconnecting from broker"); await this.consumerService.disconnect(); } }