亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

ConfigService 即使在解析后也返回字符串值

ConfigService 即使在解析后也返回字符串值

翻過高山走不出你 2023-04-20 10:02:38
所以,這是我的 NEST JS 基本應用程序。./shared/utils/config/index.tsexport default  () => ({   PORT: parseInt(process.env.PORT, 10) || 3000,   TO_PRINT_RESPONSE: JSON.parse(process.env.TO_PRINT_RESPONSE),});應用程序模塊.tsimport 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.  }}主.ts// AppModule is app.module.ts imported variableimport { 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現在:.env 正在通過dotenv模塊加載(https://docs.nestjs.com/techniques/configuration)在./shared/utils/config/index.ts中進行調試,它正在受到攻擊。所以,有人可以告訴我,當我以正確的格式( ./shared/utils/config/index.ts )加載 JSON 時,我在讀取正確數據類型的 ENV 值時哪里做錯了。謝謝&快樂編碼:)
查看完整描述

1 回答

?
白衣非少年

TA貢獻1155條經驗 獲得超0個贊

問題是 NestConfigService不會覆蓋它從環境中讀取的值,因此它們的類型將始終默認為string.


但是,您可以做的是將解析后的值分配給配置工廠中的不同屬性:


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


查看完整回答
反對 回復 2023-04-20
  • 1 回答
  • 0 關注
  • 153 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號