File

lib/shared/modules/locale/entity/locale-subscriber.ts

Description

LocaleSubscriber is an EntitySubscriber that listens to removal events for entities that have relationships with LocalizedStringEntity or LocalizedMediaEntity. When such an entity is removed, LocaleSubscriber will also remove the associated LocalizedStringEntity or LocalizedMediaEntity instances.

Example :
class MyEntity {
  @ManyToMany(() => LocalizedStringEntity, { cascade: true })
  @JoinTable()
  firstName: LocalizedStringEntity[];
}

const myEntity = new MyEntity(); entityManager.remove(myEntity); // will trigger LocaleSubscriber to remove related LocalizedStringEntity instances

Index

Methods

Constructor

constructor(logger: Logger, dataSource: DataSource)

Constructs a new LocaleSubscriber instance.

Parameters :
Name Type Optional Description
logger Logger No
  • The Logger instance used for logging messages.
dataSource DataSource No
  • The DataSource instance used to access the connection and its subscribers.

Methods

Async afterRemove
afterRemove(event: RemoveEvent)

The afterRemove event is triggered when an entity is removed. If the removed entity has relationships with LocalizedStringEntity instances, the related LocalizedStringEntity instances will also be removed.

Parameters :
Name Type Optional Description
event RemoveEvent<any> No
  • The RemoveEvent instance containing information about the removed entity.
Returns : Promise<void>

A Promise that resolves when the removal of related LocalizedStringEntity instances is complete.

import {
  DataSource,
  EntitySubscriberInterface,
  EventSubscriber,
  RemoveEvent,
} from "typeorm";
import { Inject, Injectable, Logger } from "@nestjs/common";
import { InjectDataSource } from "@nestjs/typeorm";
import { LOGGER } from "../../log/log.constants";
import { LocalizedStringEntity } from "./localized-string.entity";
import { LocalizedMediaEntity } from "./localized-media.entity";

/**
 * LocaleSubscriber is an EntitySubscriber that listens to removal events
 * for entities that have relationships with LocalizedStringEntity or LocalizedMediaEntity.
 * When such an entity is removed, LocaleSubscriber will also remove
 * the associated LocalizedStringEntity or LocalizedMediaEntity instances.
 *
 * @example
 * class MyEntity {
 *   @ManyToMany(() => LocalizedStringEntity, { cascade: true })
 *   @JoinTable()
 *   firstName: LocalizedStringEntity[];
 * }
 *
 * const myEntity = new MyEntity();
 * entityManager.remove(myEntity); // will trigger LocaleSubscriber to remove related LocalizedStringEntity instances
 */
@Injectable()
@EventSubscriber()
export class LocaleSubscriber implements EntitySubscriberInterface {
  /**
   * Constructs a new LocaleSubscriber instance.
   *
   * @param logger - The Logger instance used for logging messages.
   * @param dataSource - The DataSource instance used to access the connection and its subscribers.
   */
  constructor(
    @Inject(LOGGER) protected readonly logger: Logger,
    @InjectDataSource() private readonly dataSource: DataSource,
  ) {
    dataSource.manager.connection.subscribers.push(this);
  }

  /**
   * The afterRemove event is triggered when an entity is removed.
   * If the removed entity has relationships with LocalizedStringEntity instances,
   * the related LocalizedStringEntity instances will also be removed.
   *
   * @param event - The RemoveEvent instance containing information about the removed entity.
   * @returns A Promise that resolves when the removal of related LocalizedStringEntity instances is complete.
   */
  async afterRemove(event: RemoveEvent<any>): Promise<void> {
    const entity = event.entity;
    if (!entity) {
      return;
    }
    const localizedStringProperties = Object.values(entity).filter((value) => {
      return (
        Array.isArray(value) &&
        value.length > 0 &&
        value[0] instanceof LocalizedStringEntity
      );
    });
    if (localizedStringProperties.length > 0) {
      this.logger.verbose(
        `Removing related LocalizedStringEntity entities for ${entity.constructor.name} with ID ${event.entityId}`,
      );
      for (const relatedEntities of localizedStringProperties as LocalizedStringEntity[][]) {
        for (const relatedEntity of relatedEntities) {
          this.logger.verbose(
            `Removing LocalizedStringEntity with ID ${relatedEntity.id}`,
          );
          await event.manager.remove(relatedEntity);
          this.logger.verbose(
            `LocalizedStringEntity with ID ${relatedEntity.id} removed`,
          );
        }
      }
    }

    const localizedMediaProperties = Object.values(entity).filter((value) => {
      return (
        Array.isArray(value) &&
        value.length > 0 &&
        value[0] instanceof LocalizedMediaEntity
      );
    });
    if (localizedMediaProperties.length > 0) {
      this.logger.verbose(
        `Removing related LocalizedMediaEntity entities for ${entity.constructor.name} with ID ${event.entityId}`,
      );
      for (const relatedEntities of localizedMediaProperties as LocalizedMediaEntity[][]) {
        for (const relatedEntity of relatedEntities) {
          this.logger.verbose(
            `Removing LocalizedMediaEntity with ID ${relatedEntity.id}`,
          );
          await event.manager.remove(relatedEntity);
          this.logger.verbose(
            `LocalizedMediaEntity with ID ${relatedEntity.id} removed`,
          );
        }
      }
    }
  }
}

results matching ""

    No results matching ""