nestjs-knex icon indicating copy to clipboard operation
nestjs-knex copied to clipboard

handle connection state

Open ddtch opened this issue 2 years ago • 1 comments

Hello, I can't find how I can handle success or error connection to the database. AfterCreate method seems not working. Any ideas on how to do it? Basically, I want to have an opportunity to point callbacks on DB connected;

KnexModule.forRootAsync({
      imports: [ConfigModule],
      inject: [ConfigService],
      useFactory: (configService: ConfigService) => ({
        config: {
          log: new DbLogger(),
          debug: true,
          client: 'postgres',
          useNullAsDefault: true,
          connection: {
            host: configService.get('DB_HOST'),
            port: configService.get<number>('DB_PORT'),
            username: configService.get('DB_USERNAME'),
            password: configService.get('DB_PASSWORD'),
            database: configService.get('DB_NAME'),
          },
          afterCreate: (conn, error) => {
              // created with success or error
          },
        },
      }),
    }),

ddtch avatar Sep 01 '22 18:09 ddtch

Hello, I can't find how I can handle success or error connection to the database. AfterCreate method seems not working. Any ideas on how to do it? Basically, I want to have an opportunity to point callbacks on DB connected;

KnexModule.forRootAsync({
      imports: [ConfigModule],
      inject: [ConfigService],
      useFactory: (configService: ConfigService) => ({
        config: {
          log: new DbLogger(),
          debug: true,
          client: 'postgres',
          useNullAsDefault: true,
          connection: {
            host: configService.get('DB_HOST'),
            port: configService.get<number>('DB_PORT'),
            username: configService.get('DB_USERNAME'),
            password: configService.get('DB_PASSWORD'),
            database: configService.get('DB_NAME'),
          },
          afterCreate: (conn, error) => {
              // created with success or error
          },
        },
      }),
    }),

Issue seems to be with async behaviour, I took good amount of time to determine this issue, to resolve this issue i implemented below this solves my purpose hope this helps to you too

export class ApplicationService implements OnApplicationBootstrap {
    private logger = new Logger('common/application.service')
    constructor(@InjectKnex() private knex: Knex) {
    }
    async onApplicationBootstrap() {
        try {
            const query = await this.knex.select().fromRaw('version()')
            this.logger.log('Success: Database connecting is successful')
        } catch (databaseError) {
            this.logger.error('Failed: Error while connecting to DB')
            throw databaseError;
        }
    }
}

and added ApplicationService to app.module provider list

rajendra-kotgire avatar Mar 11 '23 19:03 rajendra-kotgire