在 Nestjs 上添加到 app.module 的 ElasticSearch 连接

Adding an ElasticSearch connection to app.module on Nestjs

我正在尝试在 app.module.ts 上与 ElasticSearch 建立连接。 我的项目文件夹如下所示:

src
 |database
   |- elasticsearch-database.module.ts
   |- es.services.ts
 |services
   |- products
      |-products.controller.ts
      |-products.module.ts
      |-products.service.ts
 app.module.ts

首先,我在 elasticsearch-database.module.ts

上创建连接
 @Global()
    @Module({
        imports: [
            ElasticsearchModule.registerAsync({
                useFactory: () => ({
                  node: 'http://localhost:9200'
                })
              })
        ],
        providers: [SearchService],
        exports: [SearchService]
    })

export class elasticSearchDatabaseModule{}

我的 SearchServicees.services.ts

@Injectable()
export class SearchService {
  constructor(private readonly elasticsearchService: ElasticsearchService) {}
}

然后,我在

上导入 elasticSearchDatabaseModule
app.module.ts

@Module({
  imports: [
    elasticSearchDatabaseModule,
    ProductsModule
  ],
  
})
export class AppModule {}

我的 ProductsModuleproducts.module.ts

@Module({
    imports: [
        elasticSearchDatabaseModule,

    ],
    controllers: [ProductsController],
    providers: [ ProductsService],
})

export class EventsModule { }

最后,在 ProductsService 上,我有

import { ElasticsearchService } from "@nestjs/elasticsearch";
@Injectable()
export class EventsService {
    constructor(
        private readonly elasticSearch      : ElasticsearchService
    ) { }
}

发生的错误是:

Potential solutions:
- If ElasticsearchService is a provider, is it part of the current EventsModule?
- If ElasticsearchService is exported from a separate @Module, is that module imported within EventsModule?
  @Module({
    imports: [ /* the Module containing ElasticsearchService */ ]
  })
 +3ms
Error: Nest can't resolve dependencies of the EventsService (?). Please make sure that the argument ElasticsearchService at index [0] is available in the EventsModule context.

如果我直接在 products.module.ts:

上创建连接,我可以完全编译而不会出错
imports: [
     
        ElasticsearchModule.register({
            node: 'http://elasticsearch:9200',
        })
    ]

但我认为如果我想在其他服务中使用该 elasticSearch 连接,这不是最佳方法。

如果您想公开该动态模块(ElasticsearchModule.registerAsync() 一个)导出的所有提供程序,则需要导出 ElasticsearchModule 模块。参见:https://docs.nestjs.com/modules#module-re-exporting

为此,只需将 ElasticsearchModule 添加到 elasticSearchDatabaseModule 模块的 exports 数组。