【问题标题】:NestJs TypeORM configuration using env filesNestJs TypeORM 配置使用 env 文件
【发布时间】:2019-06-19 01:50:01
【问题描述】:

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

【问题讨论】:

    标签: javascript node.js typescript nestjs typeorm


    【解决方案1】:

    您可以创建一个ConfigService,它读取与环境变量NODE_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]
    }),
    

    【讨论】:

    • 在这种方法中,您需要第二个配置文件才能使用 typeorm CLI
    • 你把这个放在 app.module.ts 里了吗?我收到错误说Error: No connection options were found in any of configurations file.。
    • @rhlsthrm 是的,在app.module.ts。我没有遇到这样的错误,需要更详细地查看。如果你不能解决它,也许会为它打开一个新问题。 :-)
    • @KimKern,感谢您的回复。我开了一个新问题。
    • @grexlort 是对的,例如,您将需要一个默认的导出配置文件来使用 TypeORM CLI 管理您的迁移。但这可以作为例外导入到您的 ConfigService 中,或者您可以通用并以这种方式导入它们
    猜你喜欢
    • 2020-09-22
    • 2020-12-20
    • 2021-08-05
    • 2019-09-18
    • 2019-10-31
    • 2019-05-02
    • 2020-05-11
    • 2021-04-28
    • 2021-03-16
    相关资源
    最近更新 更多