javascript - NestJs TypeORM 配置使用 env 文件
问题描述
我有两个 .env 文件,例如dev.env
和staging.env
. 我使用 typeorm 作为我的数据库 ORM。我想知道当我运行应用程序时如何让 typeorm 读取任一配置文件。Error: No connection options were found in any of configurations file
来自 typeormmodule。
解决方案
您可以创建一个读取与环境变量对应的文件的ConfigServiceNODE_ENV
:
1)NODE_ENV
在启动脚本中设置变量:
"start:dev": "cross-env NODE_ENV=dev ts-node -r tsconfig-paths/register src/main.ts",
"start:staging": "cross-env NODE_ENV=staging node dist/src/main.js",
2)读取ConfigService中对应的.env文件
@Injectable()
export class ConfigService {
private readonly envConfig: EnvConfig;
constructor() {
this.envConfig = dotenv.parse(fs.readFileSync(`${process.env.NODE_ENV}.env`));
}
get databaseHost(): string {
return this.envConfig.DATABASE_HOST;
}
}
3) 使用ConfigService
设置您的数据库连接:
TypeOrmModule.forRootAsync({
imports:[ConfigModule],
useFactory: async (configService: ConfigService) => ({
type: configService.getDatabase()
// ...
}),
inject: [ConfigService]
}),
推荐阅读
- spring - 在多模块 Gradle 项目中为独立 Camel 微服务配置 Camel-Spring
- javascript - 按升序对三个数字进行排序
- mysql - 两个查询看起来相同但行为不同
- python - 如果没有(已安装的)软件包,Jupyter 突然无法启动
- go - 不能使用 _ 作为值
- php - 在 PHP 数组 for-each 循环中,如何执行非冗余循环数据
- javascript - setTimeout 不适用于悬停时删除类
- reactjs - 如何在 Mozilla 控制台上查看我的快照?
- html - 注入 CSS 以便网站使用本地安装的 Google 字体
- reactjs - 在 mac 上安装 React