所以,这是我的 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
添加回答
举报
0/150
提交
取消