All files / src/platform/events event-bus.service.ts

0% Statements 0/27
0% Branches 0/12
0% Functions 0/4
0% Lines 0/25

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77                                                                                                                                                         
import { Injectable, Logger } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { Model, ClientSession } from 'mongoose';
import { OutboxEvent } from './schemas/outbox-event.schema';
 
@Injectable()
export class EventBusService {
  private readonly logger = new Logger(EventBusService.name);
  private readonly listeners = new Map<string, Array<(payload: any) => void>>();
 
  constructor(
    @InjectModel(OutboxEvent.name)
    private readonly outboxEventModel: Model<OutboxEvent>,
  ) {}
 
  /**
   * Publishes an event by writing it to the Outbox collection.
   * If a Mongoose session is passed, the event is saved atomically within the active transaction.
   */
  async publish(
    eventName: string,
    payload: any,
    tenantId: string,
    session?: ClientSession,
  ) {
    this.logger.log(
      `Queueing outbox event: ${eventName} for Tenant: ${tenantId}`,
    );
 
    const eventData = {
      tenantId,
      eventName,
      payload: payload || {},
      status: 'PENDING',
    };
 
    // Trigger local in-memory listeners
    const list = this.listeners.get(eventName);
    if (list) {
      for (const cb of list) {
        try {
          cb(payload);
        } catch (err) {
          this.logger.error(`Error in local event listener for ${eventName}: ${err.message}`);
        }
      }
    }
 
    if (session) {
      const [created] = await this.outboxEventModel.create([eventData], {
        session,
      });
      return created;
    }
 
    return this.outboxEventModel.create(eventData);
  }
 
  /**
   * Subscribes a local in-memory callback to an event.
   */
  subscribe(eventName: string, callback: (payload: any) => void) {
    if (!this.listeners.has(eventName)) {
      this.listeners.set(eventName, []);
    }
    this.listeners.get(eventName)!.push(callback);
    this.logger.log(`Subscribed local handler to event: ${eventName}`);
  }
 
  /**
   * Direct in-memory listener emission helper.
   */
  async emitLocal(eventName: string, payload: any) {
    this.logger.log(`Local Event Emitter: ${eventName}`);
  }
}