All files / apps/api/src/hooks create-audit-tables-on-start.ts

100% Statements 62/62
80% Branches 8/10
100% Functions 2/2
100% Lines 62/62

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 631x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 4x 4x 4x 4x 1x 1x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 2x 2x 2x 2x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 1x 1x 1x 1x 1x 1x 1x 3x 3x 3x 1x  
import { Logger, type OnApplicationBootstrap } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { pick } from 'lodash-es';
import { Repository } from 'typeorm';
 
import { Company } from '@amalia/core/models';
import { toError } from '@amalia/ext/typescript';
import { CompanyStatus } from '@amalia/tenants/companies/types';
import { AuditService } from '@amalia/tenants/monitoring/audit/core';
 
export class CreateAuditTablesOnStart implements OnApplicationBootstrap {
  private readonly logger = new Logger(CreateAuditTablesOnStart.name);
 
  public constructor(
    @InjectRepository(Company)
    private readonly companiesRepository: Repository<Company>,
    private readonly auditService: AuditService,
  ) {}
 
  public async onApplicationBootstrap() {
    const start = Date.now();
 
    const activeCompanies = await this.companiesRepository.find({
      where: {
        status: CompanyStatus.ACTIVE,
      },
    });
 
    const errors = (
      await Promise.allSettled(
        activeCompanies.map((company) =>
          this.auditService
            .createBigqueryTable(company)
            // ignore successful results (or disabled audit)
            .then(() => undefined)
            .catch((error: unknown) => ({ error: toError(error), company: pick(company, ['id', 'name']) })),
        ),
      )
    )
      .map((p) => p.status === 'fulfilled' && p.value)
      .filter(Boolean);
 
    const end = Date.now();
    const duration = Math.round(end - start);
 
    this.logger.log({
      message: `Created BigQuery Audit tables for ${activeCompanies.length - errors.length} out of ${activeCompanies.length} companies (took ${duration}ms)`,
      duration,
    });
 
    if (errors.length) {
      this.logger.error({
        message: `Failed to create BigQuery Audit tables for ${errors.length} companies`,
        results: errors,
      });
 
      return errors;
    }
 
    return null;
  }
}