Shaiq Kar
Shaiq Kar

Reputation: 13

Nest JS , Typeorm throws AlreadyHasActiveConnectionError error

I am using @nestjs/typeorm with below config to connect with the postgres db.

...
@Module({
  imports: [
    ConfigModule.forRoot({
      isGlobal: true,
      validationSchema: envValidator,
      envFilePath: '.env',
    }),
    TypeOrmModule.forRootAsync({
      imports: [ConfigModule],
      inject: [ConfigService],
      useFactory: (configService: ConfigService) => ({
        type: 'postgres',
        host: configService.get<string>('DB_HOST'),
        port: configService.get<number>('DB_PORT'),
        username: configService.get<string>('DB_USER'),
        password: configService.get<string>('DB_PASS'),
        database: configService.get<string>('DB_NAME'),
        synchronize: configService.get<boolean>('DB_SYNC'),
        autoLoadEntities: true,
        logging: configService.get<string>('NODE_ENV') === 'development',
        keepConnectionAlive: true,
      }),
    }),
    ...
  ],
})
export class AppModule {}

But sometimes when I hit any route it throws the following error.

AlreadyHasActiveConnectionError: Cannot create a new connection named "default", because connection with such name already exist and it now has an active connection session.

The Nest Js app runs as a serverless lambda on AWS.

Upvotes: 0

Views: 1128

Answers (1)

Mhamd Bahja
Mhamd Bahja

Reputation: 157

This happens because you are creating a connection with the same name in concurrent lambda execution, so try naming your connection

@Module({
  imports: [
    ConfigModule.forRoot({
      isGlobal: true,
      validationSchema: envValidator,
      envFilePath: '.env',
    }),
    TypeOrmModule.forRootAsync({
      name: 'name_it_as_you_like',  <--- HERE
      imports: [ConfigModule],
      inject: [ConfigService],
      useFactory: (configService: ConfigService) => ({
        type: 'postgres',
        host: configService.get<string>('DB_HOST'),
        port: configService.get<number>('DB_PORT'),
        username: configService.get<string>('DB_USER'),
        password: configService.get<string>('DB_PASS'),
        database: configService.get<string>('DB_NAME'),
        synchronize: configService.get<boolean>('DB_SYNC'),
        autoLoadEntities: true,
        logging: configService.get<string>('NODE_ENV') === 'development',
        keepConnectionAlive: true,
        name: 'name_it_as_you_like',  <--- HERE
      }),
    }),
    ...
  ],
})

And when you need to use it use this:

await getConnection('the_name_you_specified').manager.findOne(
      Entity,
      {
        where: {
          id: params.id,
        },
      },
    );

Upvotes: 0

Related Questions