【问题标题】:NestJS and typescript config strong types?NestJS 和 typescript 配置强类型?
【发布时间】:2020-08-02 19:22:07
【问题描述】:

我的应用程序中有一个主配置,它通过环境变量 (process.env) 表示。我怎样才能将它与下一个 JS 作为一个对象公开?在下面的示例中,我可以通过键获取值。但是我传递了一个字符串,这里没有打字稿起作用。

import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { ConfigModule } from '@nestjs/config';
import { envVarsValidator } from "../interfaces/Config";

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

import { Injectable } from '@nestjs/common';
import { ConfigService } from "@nestjs/config";

@Injectable()
export class AppService {
  constructor(private configService: ConfigService) {}

  getHello(): string {
    return this.configService.get<string>('hello'); // not what i need;
  }

}

我需要的伪代码:


export class SomeService {
  constructor(private configService: ConfigService) {}

  someLogic(): any {
    const port = this.configService.config.port;
// what i need is one main config object with highlighting properties avaliable on this object via typescript
  }

}

【问题讨论】:

    标签: javascript typescript nestjs


    【解决方案1】:

    https://docs.nestjs.com/techniques/configuration#configuration-namespaces

    例如

    config/database.config.ts JS

    export default registerAs('database', () => ({
      host: process.env.DATABASE_HOST,
      port: process.env.DATABASE_PORT || 5432
    }));
    

    并注入类型化对象

    constructor(
      @Inject(databaseConfig.KEY)
      private dbConfig: ConfigType<typeof databaseConfig>,
    ) {}
    

    【讨论】:

      【解决方案2】:

      我采用了一种稍微有点样板化的方法,用我自己的包装巢的 ConfigService 并将其作为模块的一部分导出(以及我在我的应用程序中经常使用的其他常见服务),如下所示:

      import { Injectable } from '@nestjs/common'
      import { ConfigService } from '@nestjs/config'
      
      @Injectable()
      export class ConfigurationService {
        constructor(private configService: ConfigService) {}
      
        get MY_CONFIG_STRING() {
          // this reads the value from your .env
          return this.configService.get<string>('MY_CONFIG_STRING')!
        }
      
        get MY_CONFIG_Number() {
          // this reads the value from your .env
          return this.configService.get<number>('MY_CONFIG_NUMBER')!
        }
      }
      

      用户端甜美简单:

      export class DoSomethingService {
        constructor(private configurationService: ConfigurationService) {}
      
        doSomething() {
          console.log(this.configurationService.MY_CONFIG_VALUE)
        }
      
      }
      

      只需确保在您的 ConfigurationService 模块中引导 Nest 的配置服务,如下所示:

      import { Module } from '@nestjs/common'
      import { ConfigModule, ConfigService } from '@nestjs/config'
      import { ConfigurationService } from './configuration.service'
      
      @Module({
        imports: [ConfigModule.forRoot()],
        providers: [
          ConfigService,
          ConfigurationService,
        ],
        exports: [ConfigurationService],
      })
      export class CommonModule {}
      

      【讨论】:

        【解决方案3】:

        我们开发了nest-typed-config 模块来解决这个问题。

        首先你需要创建你的配置模型:

        // config.ts
        export class Config {
            @IsString()
            public readonly host!: string;
        
            @IsNumber()
            public readonly port!: number;
        }
        

        AppModule注册TypedConfigModule

        // app.module.ts
        import { Module } from '@nestjs/common';
        import { TypedConfigModule, fileLoader } from 'nest-typed-config';
        import { AppService } from './app.service';
        import { Config } from './config';
        
        @Module({
            imports: [
                TypedConfigModule.forRoot({
                    schema: Config,
                    load: fileLoader(),
                    isGlobal: true,
                }),
            ],
            providers: [AppService],
        })
        export class AppModule {}
        

        就是这样!您现在可以在任何服务中注入Config

        // app.service.ts
        import { Config } from './config';
        
        @Injectable()
        export class AppService {
            constructor(private readonly config: Config) {}
        
            show() {
                // Full TypeScript support
                console.log(`http://${this.config.host}:${this.config.port}`)
            }
        }
        

        【讨论】:

          猜你喜欢
          • 2016-01-03
          • 2020-06-16
          • 2016-07-13
          • 2017-04-17
          • 2019-03-16
          • 2020-07-12
          • 2019-09-28
          • 2020-08-10
          • 2019-04-04
          相关资源
          最近更新 更多