Core features:
- Based on official OpenSearch client for NodeJS;
- Covered with unit and e2e tests;
- Basic module without unnecessary boilerplate.
To install the package, run:
npm install @quazex/nestjs-opensearch @opensearch-project/opensearch
To use the OpenSearch module in your NestJS application, import it into your root module (e.g., AppModule
).
import { Module } from '@nestjs/common';
import { OpenSearchModule } from '@quazex/nestjs-opensearch';
@Module({
imports: [
OpenSearchModule.forRoot({
node: 'https://localhost:9200',
auth: {
username: 'your-username',
password: 'your-password',
},
}),
],
})
export class AppModule {}
Once the module is registered, you can inject instance of Client
into your providers:
import { Injectable } from '@nestjs/common';
import { Client } from '@opensearch-project/opensearch';
import { InjectOpenSearch } from '@quazex/nestjs-opensearch';
@Injectable()
export class SearchService {
constructor(@InjectOpenSearch() private readonly client: Client) {}
async createIndex(index: string, body: any) {
return this.client.indices.create({
index,
body,
});
}
async indexDocument(index: string, id: string, body: any) {
return this.client.index({
index,
id,
body,
});
}
async search(index: string, query: any) {
return this.client.search({
index,
body: query,
});
}
}
If you need dynamic configuration, use forRootAsync
:
import { Module } from '@nestjs/common';
import { OpenSearchModule } from '@quazex/nestjs-opensearch';
@Module({
imports: [
OpenSearchModule.forRootAsync({
useFactory: async (config: SomeConfigProvider) => ({
node: config.OPENSEARCH_NODE,
auth: {
username: config.OPENSEARCH_USERNAME,
password: config.OPENSEARCH_PASSWORD,
},
}),
inject: [
SomeConfigProvider,
],
}),
],
})
export class AppModule {}
By default, this module doesn't manage client connection on application shutdown. You can read more about lifecycle hooks on the NestJS documentation page.
// main.ts
const app = await NestFactory.create(AppModule);
// Starts listening for shutdown hooks
app.enableShutdownHooks(); // <<<
await app.listen(process.env.PORT ?? 3000);
// app.bootstrap.ts
import { Injectable, OnApplicationShutdown } from '@nestjs/common';
import { Client } from '@opensearch-project/opensearch';
import { InjectOpenSearch } from '@quazex/nestjs-opensearch';
@Injectable()
export class AppBootstrap implements OnApplicationShutdown {
constructor(@InjectOpenSearch() private readonly client: Client) {}
public async onApplicationShutdown(): Promise<void> {
await this.client.close();
}
}
MIT