简体   繁体   English

NestJS 与 TypeORM:如何使用 TypeORM 连接数据库并使实例可访问

[英]NestJS with TypeORM: How to connect a DB using TypeORM and make the instance accessible

Can anyone let me know how to create an instance of the DB using TypeORM?谁能告诉我如何使用 TypeORM 创建数据库实例?

I would like to make it accessible as this service does but the Connection class is deprecated..我想让它像这个服务一样可以访问,但是 Connection class 已被弃用..

import { Inject, Injectable } from '@nestjs/common';
import { Connection, Repository } from 'typeorm';

@Injectable()
export class DatabaseService {
  constructor(@Inject('Connection') public connection: Connection) {
    console.log('!!!!')
  }
  public async getRepository<T>(entity: any): Promise<Repository<T>> {
    return this.connection.getRepository(entity);
  }
}

What is the alternative now?现在有什么选择?

How should I set up the DatabaseModule?我应该如何设置 DatabaseModule? In order to make it accessible?为了使其易于访问? Using DataSource???使用数据源???

@Module({
  imports: [
    TypeOrmModule.forRootAsync({
      imports: [ConfigModule],
      inject: [ConfigService],
      useFactory: async (configService: ConfigService) => ({
        type: 'postgres',
        host: process.env.DB_HOST,
        port: +configService.get('DB_PORT'),
        username: configService.get('DB_USER'),
        password: configService.get('DB_PASSWORD'),
        database: configService.get('DB_NAME'),
        autoLoadEntities: true,
        synchronize: true,
      })
    })
  ],
  providers: [DatabaseService]
})

export class DatabaseModule {}

Thanks in advance.提前致谢。

Try to @InjectDataSource() instead of @InjectConnection() .尝试使用@InjectDataSource()而不是@InjectConnection()

From TypeORM documentation :来自TypeORM 文档

TypeORM's DataSource holds your database connection settings and establishes initial database connection or connection pool depend on RDBMS you use. TypeORM 的 DataSource 保存您的数据库连接设置,并根据您使用的 RDBMS 建立初始数据库连接或连接池。

From the DataSource you'll be able to access everything you need: EntityManager, QueryRunner, EntityMetadata, repositories and other.从 DataSource 中,您将能够访问所需的一切:EntityManager、QueryRunner、EntityMetadata、存储库等。 Here's the documentation for the DataSource API这是 DataSource API 的文档

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM