The AOC Framework
github logodiscord logo

BACKEND

Subscribers #

Event subscribers are decorated classes that automatically register and allow you to perform operations during the lifecycle of entities.

Example #

In this example, we assign an incremental number to the code of customers when we create or update them:

@AocSubscriber
export class CustomerSubscriber implements EventSubscriber<Customer> {
  getSubscribedEntities(): EntityName<Customer>[] {
    return [ Customer ];
  }

  async beforeCreate(args: EventArgs<Customer>): Promise<void> {
    const customer = args.entity;
    if (!customer.code) {
      await this.assignCodeToCustomer(customer, args.em);
    }
  }

  async beforeUpdate(args: EventArgs<Customer>): Promise<void> {
    const customer = args.entity;
    if (!customer.code) {
      await this.assignCodeToCustomer(customer, args.em);
    }
  }

  private async assignCodeToCustomer(customer: Customer, em: EntityManager) {
    const where: FilterQuery<Customer> = { code: { $ne: null }};
    if (customer.id) {
      where.id = { $ne: customer.id };
    }
    const latestCustomer = await em.findOne(Customer, where, { orderBy: { code: 'desc' }});
    let newCode = 1;
    if (latestCustomer) {
      newCode = latestCustomer.code + 1;
    }
    customer.code = newCode;
  }
}

Complete example at quest-server/src/subscribers/customers/customer.subscriber.ts

Please note, browse Issues and Discussions in Github for more information

© 2025 Atlantis of Code. All rights reserved.
All trademarks are the property of their respective owners.