首页 > 解决方案 > NestJs TypeORM 配置使用 env 文件

问题描述

我有两个 .env 文件,例如dev.envstaging.env. 我使用 typeorm 作为我的数据库 ORM。我想知道当我运行应用程序时如何让 typeorm 读取任一配置文件。Error: No connection options were found in any of configurations file来自 typeormmodule。

标签: javascriptnode.jstypescriptnestjstypeorm

解决方案


您可以创建一个读取与环境变量对应的文件的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]
}),

推荐阅读