All files / src/session-inputs session-input.subscriber.ts

100% Statements 13/13
100% Branches 5/5
100% Functions 3/3
100% Lines 11/11

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 466x         6x 6x     6x 6x           6929x               96x     96x       10x       86x             86x      
import {
  EntitySubscriberInterface,
  EventSubscriber,
  InsertEvent,
} from 'typeorm';
import { Logger } from '@nestjs/common';
import { SessionInput } from '../core-entities/session-input.entity';
 
@EventSubscriber()
export class SessionInputSubscriber implements EntitySubscriberInterface<SessionInput> {
  private readonly logger = new Logger(SessionInputSubscriber.name);
 
  /**
   * Indicates that this subscriber only listens to SessionInput events.
   */
  listenTo() {
    return SessionInput;
  }
 
  /**
   * Called before entity is inserted to the database.
   * Automatically calculates and assigns the sequence_number for the session.
   */
  async beforeInsert(event: InsertEvent<SessionInput>): Promise<void> {
    const entity = event.entity;
 
    // If sequence_number is already set (e.g., manually set during sync), skip calculation
    if (
      entity.sequence_number !== undefined &&
      entity.sequence_number !== null
    ) {
      return;
    }
 
    // Find the current maximum sequence number for this specific session_id
    const result = await event.manager
      .createQueryBuilder(SessionInput, 'si')
      .select('MAX(si.sequence_number)', 'maxSequence')
      .where('si.session_id = :sessionId', { sessionId: entity.session_id })
      .getRawOne();
 
    // Assign the next number in sequence (1 if no previous inputs exist)
    entity.sequence_number = (result.maxSequence || 0) + 1;
  }
}