【问题标题】:How to let Kafka in the NestJs read the env file?如何让 NestJs 中的 Kafka 读取 env 文件?
【发布时间】:2021-12-29 23:51:13
【问题描述】:

我正在使用 Kafka 微服务(从 @nestjs/microservices 导入)开发一个 Nestjs 项目。

为了收听消息,我在 main.ts 中使用以下代码:

  const app = await NestFactory.createMicroservice<MicroserviceOptions>(
    AppModule,
    {
      imports: [ConfigModule],
      useFactory: async (configService: ConfigService) => ({
        transport: Transport.KAFKA,
        options: {
          client: {
            brokers: configService.get('brokers'),
          },
        },
      }),
      inject: [ConfigService],
    },
  );

      await app.listen();

我正在尝试让 nestjs 从 .env 读取代理。

它不能工作。

我得到了错误:

Argument of type '{ imports: (typeof ConfigModule)[]; useFactory: (configService: ConfigService) => Promise<{ transport: Transport; options: { client: { brokers: any; }; }; }>; inject: (typeof ConfigService)[]; }' is not assignable to parameter of type 'NestApplicationContextOptions & MicroserviceOptions'.
  Object literal may only specify known properties, and 'imports' does not exist in type 'NestApplicationContextOptions & MicroserviceOptions'.

如果删除'imports: [ConfigModule]',我有以下错误:

Argument of type '{ useFactory: (configService: ConfigService) => Promise<{ transport: Transport; options: { client: { brokers: any; }; }; }>; inject: (typeof ConfigService)[]; }' is not assignable to parameter of type 'NestApplicationContextOptions & MicroserviceOptions'.
  Object literal may only specify known properties, and 'useFactory' does not exist in type 'NestApplicationContextOptions & MicroserviceOptions'.

请帮忙:)

【问题讨论】:

  • 使用ClientsModule.registerAsync 是注入ConfigService 以检索环境的方法。瓦尔斯。编辑您的问题,向我们展示您是如何使用它的
  • 嗨,我已经更新了代码。
  • createMicroservice 没有第二个参数。它只允许{ transport, options }。见docs.nestjs.com/microservices/basics#getting-started

标签: node.js environment-variables nestjs


【解决方案1】:

我看到您在根级别包含配置模块,但您没有初始化它。我认为你应该像下面这样添加配置模块。

imports: [
    ConfigModule.forRoot({
      isGlobal: true,
    }),
    someModule,
    fooModule,
  ],
     useFactory: async (configService: ConfigService) => ({
       transport: Transport.KAFKA,
       options: {
         client: {
           brokers: configService.get('brokers'),
         },
       },
     }),
     inject: [ConfigService],
})

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-06-22
    • 1970-01-01
    • 2021-08-12
    • 2020-12-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-02
    相关资源
    最近更新 更多