gpt4 book ai didi

nestjs - 如何在 Nestjs DatabaseModule 中使用 ConfigService

转载 作者:行者123 更新时间:2023-12-04 14:11:13 24 4
gpt4 key购买 nike

我使用 nestjs typeorm 创建了一个 DatabaseModule

import { createConnection } from 'typeorm';
import { ConfigService } from '@nestjs/config';


export const databaseConnection = [
{
provide: 'DATABASE_CONNECTION',
useFactory: async (configService: ConfigService) => await createConnection({
type: configService.get('DBTYPE'),
host: configService.get('DBHOST'),
port: configService.get('DBPORT'),
username: configService.get('DBUSERNAME'),
password: configService.get('DBPASSWORD'),
database: configService.get('DBNAME'),
synchronize: true,
entities: [
__dirname + '/../**/*.entity.ts'
]
})
}
];
在启动休息服务时,我收到以下错误
Cannot read property 'get' of undefined - {"stack":["TypeError: Cannot read property 'get' of undefined

at InstanceWrapper.useFactory [as metatype] (../database/database.provider.js:9:33)
at Injector.instantiateClass (../node_modules/@nestjs/core/injector/injector.js:293:55)
at callback (../node_modules/@nestjs/core/injector/injector.js:77:41)
at process._tickCallback (internal/process/next_tick.js:68:7)
at Function.Module.runMain (internal/modules/cjs/loader.js:834:11)
at startup (internal/bootstrap/node.js:283:19)
at bootstrapNodeJSCore (internal/bootstrap/node.js:623:3)"]}
我已经导入了 ConfigModuleDatabaseModule .
有人可以帮我解决这个问题吗?
编辑
我的数据库配置
import { registerAs } from '@nestjs/config';

// Configuration factory class for database configuration.
const DatabaseConfig = registerAs('DBConfig', () => ({
DBTYPE: process.env.DATABASE_TYPE,
DBHOST: process.env.DATABASE_HOST || 'localhost',
DBPORT: process.env.DATABASE_PORT || 5432,
DBUSERNAME: process.env.DATABASE_USERNAME,
DBPASSWORD: process.env.DATABASE_PASSWORD,
DBNAME: process.env.DATABASE_NAME
}));
在 app.module.ts 导入
ConfigModule.forRoot({
isGlobal: true,
expandVariables: true,
load: [AppConfig, DatabaseConfig]
}),

最佳答案

如果ConfigService来自全局模块,需要添加 inject进入异步配置,如下所示:
由于您使用的是 config.namespace,因此您可以像 DBConfig.DBTYPE 一样调用它.

export const databaseConnection = [
{
provide: 'DATABASE_CONNECTION',
inject: [ConfigService],
useFactory: async (configService: ConfigService) => await createConnection({
type: configService.get('DBConfig.DBTYPE'),
host: configService.get('DBConfig.DBHOST'),
port: configService.get('DBConfig.DBPORT'),
username: configService.get('DBConfig.DBUSERNAME'),
password: configService.get('DBConfig.DBPASSWORD'),
database: configService.get('DBConfig.DBNAME'),
synchronize: true,
entities: [
__dirname + '/../**/*.entity.ts'
]
})
}
];
如果 ConfigService不是来自全局模块,你需要添加 两者 inject: [ConfigService]imports: [ConfigModule] .

关于nestjs - 如何在 Nestjs DatabaseModule 中使用 ConfigService,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64185541/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com