【问题标题】:TypeORM .env config not picked up in NestJS production build在 NestJS 生产版本中未选择 TypeORM .env 配置
【发布时间】:2021-08-05 08:41:19
【问题描述】:

我正在开发一个通过 TypeORM 访问 postgres 数据库的 NestJS 应用程序。在开发模式下一切正常 (npm run start:debug)。但是,在使用npm run build 构建并尝试通过node /dist/main.js 运行应用程序后,它无法启动并出现以下错误:

error: password authentication failed for user "(my system user name)"
    at Parser.parseErrorMessage (/home/(my system user name)/application/node_modules/pg-protocol/dist/parser.js:287:98)

app.module 的代码比较简陋:

import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
...
import { ConfigModule } from '@nestjs/config';

@Module({
    imports: [
        TypeOrmModule.forRoot(),
        ...
        ConfigModule.forRoot({
            isGlobal: true,
        }),
    ],
    controllers: [],
    providers: [],
})
export class AppModule {}

TypeORM 配置存储在.env 文件中。我还在构建后将其复制到dist 文件夹。从现在开始尝试让它工作 - 不必通过.env 文件,只要它在开发和生产中都有效。知道为什么没有在生产中使用配置吗?

编辑:我还尝试了其他几种配置方法,例如NestJS setup TypeOrm connection with .env and @nestjs/config 中描述的方法。部分在开发中工作,但从未在生产构建中工作。

【问题讨论】:

  • 将您的代码粘贴到您将环境传递给 typeorm 配置的位置。
  • 上面显示的代码甚至没有使用嵌套 ConfigModule/ConfigService。 TypeORM 配置是通过here 描述的环境属性完成的。 .env 文件放在package.json 旁边。

标签: typescript environment-variables nestjs typeorm


【解决方案1】:

这个问题与 TypeORM / NestJS 没有任何关系。我只是在应用程序的另一个地方使用硬连线的配置。无论如何,这是最适合我需要的 Nest 配置:

import settings from './config/settings';
import { Module } from '@nestjs/common';
import { TypeOrmModule, TypeOrmModuleOptions } from '@nestjs/typeorm';
import { ConfigModule, ConfigService } from '@nestjs/config';

@Module({
    imports: [
        ConfigModule.forRoot({
            load: [settings],
            isGlobal: true,
        }),
        
        TypeOrmModule.forRootAsync({
            imports: [ConfigModule],
            inject: [ConfigService],
            useFactory: (configService: ConfigService) =>
                Object.assign({}, configService.get<TypeOrmModuleOptions>('database'), {
                    entities: [
                        (entity classes, auto-resolution does not work),
                        ...
                    ],
                })
        }),
        ...
    ],
    controllers: [],
    providers: [],
})
export class AppModule {}

以及对应的配置文件/config/settings.ts:

export default () => ({
    database: {
        type: ...,
        host: ...,
        port: ...,
        username: ...,
        password: ...,
        database: ...,
        synchronize: ...,
        logging: ...
    },
});

【讨论】:

    猜你喜欢
    • 2019-06-19
    • 2020-09-22
    • 2020-12-20
    • 2019-10-31
    • 2022-01-24
    • 2019-09-18
    • 2022-01-17
    • 2013-04-19
    • 2019-07-11
    相关资源
    最近更新 更多