最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - ConfigService returning String Value even after parsing - Stack Overflow

programmeradmin4浏览0评论

So, here is my NEST JS Basic App.

./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.
  }
}

main.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 ing 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

Now:

  1. .env is getting loaded via dotenv module as written ()
  2. Kept debug inside ./shared/utils/config/index.ts and it is getting hit.

So, may someone please tell me, where am I doing wrong in reading the ENV value in proper datatype, when I loaded the JSON in proper format (./shared/utils/config/index.ts).

Thanks & Happy Coding :)

So, here is my NEST JS Basic App.

./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.
  }
}

main.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 ing 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

Now:

  1. .env is getting loaded via dotenv module as written (https://docs.nestjs./techniques/configuration)
  2. Kept debug inside ./shared/utils/config/index.ts and it is getting hit.

So, may someone please tell me, where am I doing wrong in reading the ENV value in proper datatype, when I loaded the JSON in proper format (./shared/utils/config/index.ts).

Thanks & Happy Coding :)

Share Improve this question asked Oct 5, 2020 at 18:38 Ankur VermaAnkur Verma 5,93316 gold badges61 silver badges95 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 6

The problem is that Nest's ConfigService will not override the values it has read from the environment, hence their types will always default to string.

What you can do, however, is to assign the parsed values to different properties in your config-factory:

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

If you then access those values, the types will be correct:

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

评论列表(0)

  1. 暂无评论