@nestjs/typeorm How to get current connection with v0.3.0 of typeorm in a custom decorator?

Viewed 775

I used to have:

import { getManager } from "typeorm";

return getManager()
  .count(entity, {
    ...where,
  })
  .then((count) => count < 1);

to use the current connection in a validation decorator and access to database.

But now with the version 0.3.0 of typeorm, getManager() is deprecated and I get the following error:

`ConnectionNotFoundError: Connection default was not found`

How should I use the new DataSource API to get the current connection using Nest.js in external scripts like validation decorators?

1 Answers

I have dealt with the following error with "typeorm": "0.3.6", before, so hopes that my experience will be relevant for you.

Instead of using getManager I am using entityManager but result is the same.

Here is the example for your case:

test.module.ts

@Module({
  imports: [
    TypeOrmModule.forRoot(postgresConfig), // <- connection configs
    TypeOrmModule.forFeature([
      TestEntity,
    ]),
  ],
  controllers: [],
  providers: [TestService],
})
export class TestModule {}

test.service.ts

@Injectable()
export class TestService implements OnApplicationBootstrap {
  constructor(
    @InjectEntityManager()
    private readonly entityManager: EntityManager,
  )

  async onApplicationBootstrap(): Promise<void> {
    const count = await this.entityManager.getRepository(TestEntity).count('query');
    console.log(count);
  }
}

You should also have created a typeorm entities for that.

If we are talking about migrations you could use an ormconfig.json, but also there was a problem with using typeorm combined with test frameworks like Jest and if you case is relevant with it, just mention it, and I'll find an example in on of my projects.

It should be something relevant with creating manual connections without decorator like:

export const getDatabaseConnectionOptions = (config): PostgresConnectionOptions => {
    return {
        type: 'postgres',
        logging: config.db.logging,
        connectTimeoutMS: config.db.master.connectionTimeoutMillis,
        uuidExtension: 'uuid-ossp',
        extra: {
            idleTimeoutMillis: config.db.master.idleTimeoutMillis,
            max: config.db.master.max,
            keepalives_idle: config.db.master.keepalives_idle,
        },
        entities: process.env.TS_NODE
            ? [path.join(process.cwd(), 'src/**/*.entity.ts')]
            : [path.join(process.cwd(), 'dist/**/*.entity.js')],
        migrations: process.env.TS_NODE ? ['src/typeorm_migrations/*.ts'] : ['dist/typeorm_migrations/*.js'],
        migrationsTableName: 'typeorm_migrations',
        namingStrategy: new DatabaseNamingStrategy(),
        replication: {
            master: {
                host: config.db.master.host,
                port: config.db.master.port,
                username: config.db.master.user,
                password: config.db.master.password,
                database: config.db.master.database,
            },
            slaves: [
                {
                    host: config.db.slave.host,
                    port: config.db.slave.port,
                    username: config.db.slave.user,
                    password: config.db.slave.password,
                    database: config.db.slave.database,
                },
            ],
        },
        cli: {
            migrationsDir: 'src/typeorm_migrations',
        },
    };
};

export const createDatabaseConnection = async (config): Promise<Connection> => {
    // Setup TypeDI
    useContainer(Container);

    // Setup typeorm-transactional-cls-hooked
    initializeTransactionalContext();
    patchTypeORMRepositoryWithBaseRepository();

    return await createConnection(config);
};
    const connection = await createDatabaseConnection(getDatabaseConnectionOptions(config));
    const { app } = createAppApi();

and then access to managers or entities via connection props.

Related