如何在NestJS中通过托管身份使用TypeORM连接MSSQL数据库?
TypeORM 托管身份连接 MSSQL 及 Repository 初始化问题解答
1. 通过Azure App Service托管身份连接MSSQL
TypeORM的MSSQL适配基于tedious驱动,可直接将Azure托管身份的认证逻辑整合到TypeOrmModuleOptions中。你需要移除原配置里的username和password字段,添加authentication和options配置块,修改后的代码如下:
createTypeOrmOptions(): TypeOrmModuleOptions { return { name: 'default', type: 'mssql', host: this.configService.get<string>("DATABASE_HOST"), port: Number(this.configService.get<number>("DATABASE_PORT")), database: this.configService.get<string>("DATABASE_DB"), synchronize: false, logging: true, // 新增托管身份认证配置 authentication: { type: 'azure-active-directory-msi-app-service' }, options: { encrypt: true } }; }
注意:请确保你的typeorm和tedious依赖是最新版本,旧版本可能不支持该Azure AD认证类型。
2. 初始化Repository时指定数据库连接对象
TypeORM支持明确指定连接来初始化Repository,有两种常见方式:
- 直接在
getRepository中传入连接名称:import { getRepository } from 'typeorm'; import { YourEntity } from './your.entity'; // 使用名为'default'的连接初始化Repository const yourRepo = getRepository(YourEntity, 'default'); - 通过已获取的连接实例获取Repository:
import { getConnection } from 'typeorm'; import { YourEntity } from './your.entity'; const targetConnection = getConnection('default'); const yourRepo = targetConnection.getRepository(YourEntity);
这两种方式都能确保你使用指定的数据库连接对应的Repository。
内容的提问来源于stack exchange,提问作者user3409127
相关产品推荐
相关产品推荐

