我需要在运行时将用户名和密码传递给TypeORM。

4
在NodeJS(NestJS)中,我使用TypeORM连接到数据库(Oracle)。我希望在应用程序运行期间传递用户名和密码。由于安全原因,在我的公司中,安全设置是针对每个用户创建一个数据库模式。他使用他的DB凭据登录应用程序。我知道这不是业界非常流行的做法。
const connection = await createConnection({
    type: "oracle",
    host: "localhost",
    port: 3306,
    username: "test", // this need to pass during run time 
    password: "test", // same thing for the password 
    database: "test"
});

你能与我分享一些关于如何在TypeORM和Node.js/NestJs上实现这个的参考/提示吗?

谢谢。

1个回答

1
您可以在根级别使用 TypeORM 注册,并使用配置服务提供连接详细信息:
    TypeOrmModule.forRootAsync({
        imports: [ConfigModule],
        useFactory: (config: ConfigService) => ({
            host: config.get('DB_HOST'),
            username: config.get('DB_USER'),
            password: config.get('DB_PASSWORD'),
            database: config.get('DB_NAME'),
            entities: [__dirname + '/**/*.entity{.ts,.js}'],
            port: 3306,
            type: 'oracle',
        }),
        inject: [ConfigService],
    }),

ConfigService是一个简单的服务,实现了一个get函数,提供特定请求的配置。

更多信息请参见:https://docs.nestjs.com/techniques/database#async-configuration


如果您需要将配置作为Promise获取,使用await在返回对象之前在useFactory回调上是否可以/推荐使用? - Alejandro Barone

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接