All files / src/modules/common/database database.module.ts

0% Statements 0/25
0% Branches 0/3
0% Functions 0/6
0% Lines 0/23

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 63 64 65                                                                                                                                 
import { Global, Inject, Module, OnModuleInit } from '@nestjs/common';
import ENV from 'src/shared/env';
import { logger } from 'src/shared/logger';
import { DataSource } from 'typeorm';
import {
  MONGO_AUTH_TOKEN,
  POSTGRES_ACCOUNT_TOKEN,
  POSTGRES_AUTH_TOKEN,
} from './shared/database.const';
import { DatabaseProviders } from './shared/database.provider';
import { DatabaseRepositories } from './shared/database.repositories';
import { Mongoose } from 'mongoose';
 
@Global()
@Module({
  providers: [...DatabaseProviders, ...DatabaseRepositories],
  exports: [...DatabaseRepositories],
})
export class DatabaseModule implements OnModuleInit {
  constructor(
    @Inject(POSTGRES_AUTH_TOKEN) private readonly authDataSource: DataSource,
    @Inject(POSTGRES_ACCOUNT_TOKEN) private readonly accountDataSource: DataSource,
 
    @Inject(MONGO_AUTH_TOKEN) private readonly mongoose: Mongoose,
  ) {}
 
  async onModuleInit() {
    await Promise.all([
      this.authDataSource
        .initialize()
        .then(() =>
          logger.info(
            `Connected to PostgresDB: ${ENV.POSTGRES.AUTH.HOST} [${ENV.POSTGRES.AUTH.DATABASE}]`,
          ),
        )
        .catch((err) => {
          logger.error(
            `Failed to connect to PostgresDB: ${ENV.POSTGRES.AUTH.HOST} [${ENV.POSTGRES.AUTH.DATABASE}]`,
          );
          throw err;
        }),
      this.accountDataSource
        .initialize()
        .then(() =>
          logger.info(
            `Connected to PostgresDB: ${ENV.POSTGRES.ACCOUNT.HOST} [${ENV.POSTGRES.AUTH.DATABASE}]`,
          ),
        )
        .catch((err) => {
          logger.error(
            `Failed to connect to PostgresDB: ${ENV.POSTGRES.ACCOUNT.HOST} [${ENV.POSTGRES.AUTH.DATABASE}]`,
          );
          throw err;
        }),
    ]);
 
    if (this.mongoose.connection.readyState === 1)
      logger.info(`Connected to MongoDB: ${ENV.MONGODB.AUTH.HOST} [${ENV.MONGODB.AUTH.DATABASE}]`);
    else Iif (this.mongoose.connection.readyState === 0)
      logger.error(
        `Unable to connect to MongoDB: ${ENV.MONGODB.AUTH.HOST} [${ENV.MONGODB.AUTH.DATABASE}]`,
      );
  }
}