簡體   English   中英

NestJS 與 TypeORM:如何使用 TypeORM 連接數據庫並使實例可訪問

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

誰能告訴我如何使用 TypeORM 創建數據庫實例?

我想讓它像這個服務一樣可以訪問,但是 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);
  }
}

現在有什么選擇?

我應該如何設置 DatabaseModule? 為了使其易於訪問? 使用數據源???

@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 {}

提前致謝。

嘗試使用@InjectDataSource()而不是@InjectConnection()

來自TypeORM 文檔

TypeORM 的 DataSource 保存您的數據庫連接設置,並根據您使用的 RDBMS 建立初始數據庫連接或連接池。

從 DataSource 中,您將能夠訪問所需的一切:EntityManager、QueryRunner、EntityMetadata、存儲庫等。 這是 DataSource API 的文檔

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM