Skip to main content
Skip table of contents

Extend Api Calls

Every API Call from Features can be extended, bevor and after his execution.

Example to send Emails after a create of a Model:

TYPESCRIPT
import { Inject, Injectable, OnModuleInit } from '@nestjs/common';
import { DamageReportEntity } from './damage-reports.entity';
import { HookRegistryService } from '@nxtlvls/generic-api';
import { MailService } from '../../core/mail/services/mail.service';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import {ConfigService} from "../../core/config/config.service";

@Injectable()
export class HooksInitializer implements OnModuleInit {
  constructor(
    @Inject(`${DamageReportEntity.name}RegistryService`)
    private hookRegistry: HookRegistryService,
    private _mailService: MailService,
    @InjectRepository(DamageReportEntity)
    private readonly _repository: Repository<DamageReportEntity>,
    private readonly _configService: ConfigService
  ) {}
  onModuleInit() {
    this.hookRegistry.registerHook(
      'DamageReportEntity.after.create',
      this.sendMailAfterCreate.bind(this)
    );
  }
  async sendMailAfterCreate(entity) {
    const report = await this._repository.findOne({
      where: { id: entity.id },
      relations: [
        'tireGuarantee',
        'tireGuarantee.user',
        'tireGuarantee.tire_variant',
      ],
    });

    await this._mailService.sendMail(
      'info',
      {
        receiverMail: this._configService.get('GUARANTEE_REQUEST_RECEIVER') ??
          'demo@next-levels.de'
      },
      {
        ...report,
        new_tire_invoice_id: report.new_tire_invoice_id,
        user_first_name: report.tireGuarantee.user.first_name,
        user_last_name: report.tireGuarantee.user.last_name,
        user_email: report.tireGuarantee.user.email,
        tireGuarantee_id: report.tireGuarantee.id,
        tireGuarantee_tire_variant_article_number:
          report.tireGuarantee.tire_variant.article_number,
      } as Record<string, any>
    );
  }
}
JavaScript errors detected

Please note, these errors can depend on your browser setup.

If this problem persists, please contact our support.