【问题标题】:ConfigService returning String Value even after parsingConfigService 解析后返回字符串值
【发布时间】:2021-01-20 15:48:10
【问题描述】:

所以,这是我的 NEST JS 基本应用程序。

./shared/utils/config/index.ts

export default  () => ({
   PORT: parseInt(process.env.PORT, 10) || 3000,
   TO_PRINT_RESPONSE: JSON.parse(process.env.TO_PRINT_RESPONSE),
});

app.module.ts

import CONFIG from './shared/utils/config/';
@Module({
      imports: [ 
        ConfigModule.forRoot({
          isGlobal: true,
          load: [ CONFIG ],
        })
      ]
      // some more Module Decorator Config
})
export class AppModule implements NestModule {
  configure(consumer: MiddlewareConsumer) {
      consumer
        .apply(AuthMiddleware)
        .forRoutes({ path: '/someurl', method: RequestMethod.ALL });
      // some more configuration code.
  }
}

ma​​in.ts

// AppModule is app.module.ts imported variable
import { ConfigService } from '@nestjs/config';

async function bootstrap() {
    const app: INestApplication = await NestFactory.create(AppModule, {
       logger: console,
    });

    const configService = app.get(ConfigService);
    console.log(typeof configService.get<Boolean>('TO_PRINT_RESPONSE'));

    /* this is coming as String even when:
     * 1. I place <Boolean> as a type (I know its of no use, since it does not change the datatype)
     * 2. But in config/index.ts I parsed it in BOOLEAN using JSON.parse()
     */  
}
bootstrap();

.env

 PORT=5000
 TO_PRINT_RESPONSE=true

现在:

  1. .env 正在通过 dotenv 模块加载(https://docs.nestjs.com/techniques/configuration
  2. ./shared/utils/config/index.ts 中保持调试,它会受到影响。

所以,有人可以告诉我,当我以正确的格式(./shared/utils/config/index.ts强>)。

感谢和快乐编码:)

【问题讨论】:

    标签: javascript node.js typescript environment-variables nestjs


    【解决方案1】:

    问题在于 Nest 的 ConfigService 不会覆盖它从环境中读取的值,因此它们的类型将始终默认为 string

    但是,您可以将解析后的值分配给 config-factory 中的不同属性:

    export default  () => ({
       port: parseInt(process.env.PORT, 10) || 3000,
       toPrintResponse: JSON.parse(process.env.TO_PRINT_RESPONSE),
    });
    

    如果您随后访问这些值,则类型将是正确的:

    console.log(typeof configService.get('toPrintResponse')); // prints boolean
    console.log(typeof configService.get('port')); // prints number
    

    【讨论】:

    • 所以,一切都很好,如果我创建一个不同的命名变量,我能够获取所有值(带有数据类型),但是我们可以做些什么来覆盖这个设置。跨度>
    • 据我所知,不幸的是没有办法覆盖这些。
    猜你喜欢
    • 2020-01-25
    • 2020-07-10
    • 1970-01-01
    • 2018-09-20
    • 1970-01-01
    • 2013-10-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多