3
votes

Is it possible to use connection class as provide like here?

import { Connection, createConnection } from 'typeorm';

export const databaseProviders = [{
  provide: Connection,
  useFactory: async () => await createConnection({
    type: 'postgres',
    host: 'localhost',
    port: 5432,
    username: 'postgres',
    password: 'postgres',
    database: 'testo',
    entities: [
      __dirname + '/../**/*.entity{.ts,.js}',
    ],
    logging: true,
    synchronize: true,
  }),
}];

To make imports work like:

constructor(
  private connection: Connection,
) {
  this.repository = connection.getRepository(Project);
}

In that case nestjs can't find dependency. I guess the problem is in typeorm, it is compiled to plain es5 function. But maybe there a solution for this?

repository to reproduce

UPDATE:

I found acceptable solution nestjs typeorm module, but don't understand why my Connection class is not worked, but it works well with strings. Hope @kamil-myƛliwiec will help to understand.

  modules: [
    TypeOrmModule.forRoot(
      [
        Build,
        Project,
      ],
      {
        type: 'postgres',
        host: 'localhost',
        port: 5432,
        username: 'postgres',
        password: 'postgres',
        database: 'testo',
        entities: [
          Build,
        ],
        logging: true,
        synchronize: true,
      }),
  ],
  // And the n inject like this by entity name
  @InjectRepository(Build) private repository: Repository<Build>,