@xnestjs/elasticsearch 1.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2022 Panates
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,86 @@
1
+ # @xnestjs/elasticsearch
2
+
3
+ NestJS extension library for ElasticSearch
4
+
5
+ ## Install
6
+
7
+ ```sh
8
+ npm install @xnestjs/elasticsearch
9
+ # or using yarn
10
+ yarn add @xnestjs/elasticsearch
11
+ ```
12
+
13
+ ## Usage
14
+
15
+ ### Register sync
16
+
17
+ An example of nestjs module that import the @xnestjs/elasticsearch
18
+
19
+ ```ts
20
+ // module.ts
21
+ import { Module } from '@nestjs/common';
22
+ import { ElasticsearchModule } from '@xnestjs/elasticsearch';
23
+
24
+ @Module({
25
+ imports: [
26
+ ElasticsearchModule.forRoot({
27
+ useValue: {
28
+ node: 'http://localhost:9201',
29
+ },
30
+ }),
31
+ ],
32
+ })
33
+ export class MyModule {
34
+ }
35
+ ```
36
+
37
+ ### Register async
38
+
39
+ An example of nestjs module that import the @xnestjs/elasticsearch async
40
+
41
+ ```ts
42
+ // module.ts
43
+ import { Module } from '@nestjs/common';
44
+ import { ElasticsearchModule } from '@xnestjs/elasticsearch';
45
+
46
+ @Module({
47
+ imports: [
48
+ ElasticsearchModule.forRootAsync({
49
+ inject: [ConfigModule],
50
+ useFactory: (config: ConfigService) => ({
51
+ node: config.get('ELASTIC_NODE'),
52
+ }),
53
+ }),
54
+ ]
55
+ })
56
+ export class MyModule {
57
+ }
58
+ ```
59
+
60
+ ## Environment Variables
61
+
62
+ The library supports configuration through environment variables. Environment variables below is accepted.
63
+ All environment variables starts with prefix (MONGODB_). This can be configured while registering the module.
64
+
65
+ | Environment Variable | Type | Default | Description |
66
+ |--------------------------------------|---------|-----------------------|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
67
+ | ELASTIC_NODE | String | http://localhost:9200 | Elasticsearch node settings, if there is only one node. Required if `NODES` or `CLOUD_ID` is not set. |
68
+ | ELASTIC_NODES | String | | Elasticsearch node settings, if there is only one node. Required if `NODE` or `CLOUD_ID` is not set. |
69
+ | ELASTIC_NAME | String | elasticsearch-js | A name for client |
70
+ | ELASTIC_MAX_RESPONSE_SIZE | Number | | When configured, verifies that the uncompressed response size is lower than the configured number. If it's higher, it will abort the request. |
71
+ | ELASTIC_MAX_COMPRESSED_RESPONSE_SIZE | Number | | When configured, verifies that the compressed response size is lower than the configured number. If it's higher, it will abort the request. |
72
+ | ELASTIC_MAX_RETRIES | Number | 3 | Max number of retries for each request |
73
+ | ELASTIC_REQUEST_TIMEOUT | Number | 30000 | Max request timeout in milliseconds for each request |
74
+ | ELASTIC_PING_TIMEOUT | Number | 3000 | Max number of milliseconds a `ClusterConnectionPool` will wait when pinging nodes before marking them dead |
75
+ | ELASTIC_AUTH_USERNAME | String | | BasicAuth username |
76
+ | ELASTIC_AUTH_PASSWORD | String | | BasicAuth password |
77
+ | ELASTIC_AUTH_BEARER | String | | BearerAuth bearer header value |
78
+ | ELASTIC_AUTH_API_KEY | String | | ApiKeyAuth api key |
79
+ | ELASTIC_API_KEY_ID | String | | ApiKeyAuth api key id |
80
+ | ELASTIC_TLS | Boolean | False | Enabled the TLS connection |
81
+ | ELASTIC_TLS_CA_CERT | String | | Optionally override the trusted CA certificates. Default is to trust the well-known CAs curated by Mozilla. Mozilla's CAs are completely replaced when CAs are explicitly specified using this option. |
82
+ | ELASTIC_TLS_CERT_FILE | String | | The File that contains Cert chains in PEM format. |
83
+ | ELASTIC_TLS_KEY_FILE | String | | The File that contains private keys in PEM format. |
84
+ | ELASTIC_TLS_KEY_PASSPHRASE | String | | PFX or PKCS12 encoded private key and certificate chain. |
85
+ | ELASTIC_TLS_REJECT_UNAUTHORIZED | Boolean | False | If true the server will reject any connection which is notauthorized with the list of supplied CAs. This option only has an effect if requestCert is true. |
86
+ | ELASTIC_CA_FINGERPRINT | String | | If configured, verifies that the fingerprint of the CA certificate that has signed the certificate of the server matches the supplied fingerprint; only accepts SHA256 digest fingerprints |
@@ -0,0 +1,5 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.ELASTICSEARCH_MODULE_ID = exports.ELASTICSEARCH_CONNECTION_OPTIONS = void 0;
4
+ exports.ELASTICSEARCH_CONNECTION_OPTIONS = Symbol('ELASTICSEARCH_CONNECTION_OPTIONS');
5
+ exports.ELASTICSEARCH_MODULE_ID = Symbol('ELASTICSEARCH_MODULE_ID');
@@ -0,0 +1,198 @@
1
+ "use strict";
2
+ var ElasticsearchCoreModule_1;
3
+ Object.defineProperty(exports, "__esModule", { value: true });
4
+ exports.ElasticsearchCoreModule = void 0;
5
+ const tslib_1 = require("tslib");
6
+ const node_assert_1 = tslib_1.__importDefault(require("node:assert"));
7
+ const crypto = tslib_1.__importStar(require("node:crypto"));
8
+ const node_process_1 = tslib_1.__importDefault(require("node:process"));
9
+ const objects_1 = require("@jsopen/objects");
10
+ const common_1 = require("@nestjs/common");
11
+ const elasticsearch_1 = require("@nestjs/elasticsearch");
12
+ const colors = tslib_1.__importStar(require("ansi-colors"));
13
+ const putil_varhelpers_1 = require("putil-varhelpers");
14
+ const constants_js_1 = require("./constants.js");
15
+ const CLIENT_TOKEN = Symbol('CLIENT_TOKEN');
16
+ let ElasticsearchCoreModule = ElasticsearchCoreModule_1 = class ElasticsearchCoreModule {
17
+ /**
18
+ *
19
+ */
20
+ static forRoot(moduleOptions) {
21
+ const connectionOptions = this._readConnectionOptions(moduleOptions.useValue || {}, moduleOptions.envPrefix);
22
+ return this._createDynamicModule(moduleOptions, {
23
+ global: moduleOptions.global,
24
+ providers: [
25
+ {
26
+ provide: constants_js_1.ELASTICSEARCH_CONNECTION_OPTIONS,
27
+ useValue: connectionOptions,
28
+ },
29
+ ],
30
+ });
31
+ }
32
+ /**
33
+ *
34
+ */
35
+ static forRootAsync(asyncOptions) {
36
+ node_assert_1.default.ok(asyncOptions.useFactory, 'useFactory is required');
37
+ return this._createDynamicModule(asyncOptions, {
38
+ global: asyncOptions.global,
39
+ providers: [
40
+ {
41
+ provide: constants_js_1.ELASTICSEARCH_CONNECTION_OPTIONS,
42
+ inject: asyncOptions.inject,
43
+ useFactory: async (...args) => {
44
+ const opts = await asyncOptions.useFactory(...args);
45
+ return this._readConnectionOptions(opts, asyncOptions.envPrefix);
46
+ },
47
+ },
48
+ ],
49
+ });
50
+ }
51
+ static _createDynamicModule(opts, metadata) {
52
+ const token = opts.token ?? elasticsearch_1.ElasticsearchService;
53
+ const logger = typeof opts.logger === 'string' ? new common_1.Logger(opts.logger) : opts.logger;
54
+ const exports = [constants_js_1.ELASTICSEARCH_CONNECTION_OPTIONS, ...(metadata.exports ?? [])];
55
+ const providers = [
56
+ ...(metadata.providers ?? []),
57
+ {
58
+ provide: common_1.Logger,
59
+ useValue: logger,
60
+ },
61
+ {
62
+ provide: CLIENT_TOKEN,
63
+ useExisting: elasticsearch_1.ElasticsearchService,
64
+ },
65
+ {
66
+ provide: constants_js_1.ELASTICSEARCH_MODULE_ID,
67
+ useValue: crypto.randomUUID(),
68
+ },
69
+ ];
70
+ if (token !== elasticsearch_1.ElasticsearchService) {
71
+ exports.push(token);
72
+ providers.push({
73
+ provide: token,
74
+ useExisting: elasticsearch_1.ElasticsearchService,
75
+ });
76
+ }
77
+ class InnerProvidersModule {
78
+ }
79
+ return {
80
+ module: ElasticsearchCoreModule_1,
81
+ providers,
82
+ // global: true,
83
+ imports: [
84
+ elasticsearch_1.ElasticsearchModule.registerAsync({
85
+ imports: [
86
+ {
87
+ module: InnerProvidersModule,
88
+ providers: metadata.providers,
89
+ exports: metadata.providers,
90
+ },
91
+ ],
92
+ inject: [constants_js_1.ELASTICSEARCH_CONNECTION_OPTIONS],
93
+ useFactory: async (connectionOptions) => {
94
+ return connectionOptions;
95
+ },
96
+ }),
97
+ ],
98
+ exports,
99
+ };
100
+ }
101
+ static _readConnectionOptions(moduleOptions, prefix = 'ELASTIC_') {
102
+ const options = (0, objects_1.clone)(moduleOptions);
103
+ const env = node_process_1.default.env;
104
+ options.node = options.node || env[prefix + 'NODE'];
105
+ if (options.node) {
106
+ if (typeof options.node === 'string' && options.node.includes(','))
107
+ options.node.split(/\s*,\s*/);
108
+ }
109
+ else {
110
+ options.nodes = options.nodes || env[prefix + 'NODES'];
111
+ if (options.nodes) {
112
+ if (typeof options.nodes === 'string' && options.nodes.includes(','))
113
+ options.nodes.split(/\s*,\s*/);
114
+ }
115
+ }
116
+ if (!(options.node || options.nodes))
117
+ options.node = 'http://localhost:9200';
118
+ options.maxRetries = options.maxRetries ?? (0, putil_varhelpers_1.toInt)(env[prefix + 'MAX_RETRIES']);
119
+ options.requestTimeout = options.requestTimeout ?? (0, putil_varhelpers_1.toInt)(env[prefix + 'REQUEST_TIMEOUT']);
120
+ options.pingTimeout = options.pingTimeout ?? (0, putil_varhelpers_1.toInt)(env[prefix + 'PING_TIMEOUT']);
121
+ if (options.tls == null && (0, putil_varhelpers_1.toBoolean)(env[prefix + 'TLS'])) {
122
+ options.tls = {
123
+ ca: [env[prefix + 'TLS_CA_CERT'] || ''],
124
+ cert: env[prefix + 'TLS_CERT_FILE'],
125
+ key: env[prefix + 'TLS_KEY_FILE'],
126
+ passphrase: env[prefix + 'TLS_KEY_PASSPHRASE'],
127
+ rejectUnauthorized: (0, putil_varhelpers_1.toBoolean)(env[prefix + 'TLS_REJECT_UNAUTHORIZED']),
128
+ checkServerIdentity: (host, cert) => {
129
+ if (cert.subject.CN !== host) {
130
+ return new Error(`Certificate CN (${cert.subject.CN}) does not match host (${host})`);
131
+ }
132
+ },
133
+ };
134
+ }
135
+ options.name = options.name ?? env[prefix + 'NAME'];
136
+ if (!options.auth) {
137
+ if (env[prefix + 'AUTH_USERNAME']) {
138
+ options.auth = {
139
+ username: env[prefix + 'AUTH_USERNAME'],
140
+ password: env[prefix + 'AUTH_PASSWORD'] || '',
141
+ };
142
+ }
143
+ else if (env[prefix + 'AUTH_BEARER']) {
144
+ options.auth = {
145
+ bearer: env[prefix + 'AUTH_BEARER'],
146
+ };
147
+ }
148
+ else if (env[prefix + 'AUTH_API_KEY']) {
149
+ if (env[prefix + 'API_KEY_ID'])
150
+ options.auth = {
151
+ apiKey: {
152
+ id: env[prefix + 'API_KEY_ID'],
153
+ api_key: env[prefix + 'API_KEY'],
154
+ },
155
+ };
156
+ options.auth = {
157
+ apiKey: env[prefix + 'API_KEY'],
158
+ };
159
+ }
160
+ }
161
+ options.caFingerprint = options.caFingerprint ?? env[prefix + 'CA_FINGERPRINT'];
162
+ options.maxResponseSize = options.maxResponseSize ?? (0, putil_varhelpers_1.toInt)(env[prefix + 'MAX_RESPONSE_SIZE']);
163
+ options.maxCompressedResponseSize =
164
+ options.maxCompressedResponseSize ?? (0, putil_varhelpers_1.toInt)(env[prefix + 'MAX_COMPRESSED_RESPONSE_SIZE']);
165
+ return options;
166
+ }
167
+ /**
168
+ *
169
+ * @constructor
170
+ */
171
+ constructor(client, logger, connectionOptions) {
172
+ this.client = client;
173
+ this.logger = logger;
174
+ this.connectionOptions = connectionOptions;
175
+ }
176
+ async onApplicationBootstrap() {
177
+ if (this.logger) {
178
+ const options = this.connectionOptions;
179
+ const nodes = options.node || options.nodes;
180
+ this.logger.log(`Connecting to ElasticSearch at ${colors.blue(String(nodes))}`);
181
+ common_1.Logger.flush();
182
+ await this.client.ping({}).catch(e => {
183
+ this.logger.error('ElasticSearch connection failed: ' + e.message);
184
+ throw e;
185
+ });
186
+ }
187
+ }
188
+ onApplicationShutdown() {
189
+ return this.client.close();
190
+ }
191
+ };
192
+ exports.ElasticsearchCoreModule = ElasticsearchCoreModule;
193
+ exports.ElasticsearchCoreModule = ElasticsearchCoreModule = ElasticsearchCoreModule_1 = tslib_1.__decorate([
194
+ tslib_1.__param(0, (0, common_1.Inject)(CLIENT_TOKEN)),
195
+ tslib_1.__param(2, (0, common_1.Inject)(constants_js_1.ELASTICSEARCH_CONNECTION_OPTIONS)),
196
+ tslib_1.__metadata("design:paramtypes", [elasticsearch_1.ElasticsearchService,
197
+ common_1.Logger, Object])
198
+ ], ElasticsearchCoreModule);
@@ -0,0 +1,32 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.ElasticsearchModule = void 0;
4
+ const elasticsearch_core_module_js_1 = require("./elasticsearch-core.module.js");
5
+ /**
6
+ * The ElasticsearchModule class is responsible for providing integration with Elasticsearch
7
+ * through dynamic module configurations. It allows synchronous and asynchronous setup of
8
+ * Elasticsearch configurations for use in a Node.js application.
9
+ */
10
+ class ElasticsearchModule {
11
+ /**
12
+ * Configures and returns the dynamic module for the Elasticsearch integration.
13
+ *
14
+ */
15
+ static forRoot(options) {
16
+ return {
17
+ module: ElasticsearchModule,
18
+ imports: [elasticsearch_core_module_js_1.ElasticsearchCoreModule.forRoot(options || {})],
19
+ };
20
+ }
21
+ /**
22
+ * Configures and returns the async dynamic module for the Elasticsearch integration.
23
+ *
24
+ */
25
+ static forRootAsync(options) {
26
+ return {
27
+ module: ElasticsearchModule,
28
+ imports: [elasticsearch_core_module_js_1.ElasticsearchCoreModule.forRootAsync(options)],
29
+ };
30
+ }
31
+ }
32
+ exports.ElasticsearchModule = ElasticsearchModule;
package/cjs/index.js ADDED
@@ -0,0 +1,9 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.ElasticsearchService = void 0;
4
+ const tslib_1 = require("tslib");
5
+ tslib_1.__exportStar(require("./constants.js"), exports);
6
+ tslib_1.__exportStar(require("./elasticsearch.module.js"), exports);
7
+ tslib_1.__exportStar(require("./types.js"), exports);
8
+ var elasticsearch_1 = require("@nestjs/elasticsearch");
9
+ Object.defineProperty(exports, "ElasticsearchService", { enumerable: true, get: function () { return elasticsearch_1.ElasticsearchService; } });
@@ -0,0 +1,3 @@
1
+ {
2
+ "type": "commonjs"
3
+ }
package/cjs/types.js ADDED
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
@@ -0,0 +1,2 @@
1
+ export const ELASTICSEARCH_CONNECTION_OPTIONS = Symbol('ELASTICSEARCH_CONNECTION_OPTIONS');
2
+ export const ELASTICSEARCH_MODULE_ID = Symbol('ELASTICSEARCH_MODULE_ID');
@@ -0,0 +1,195 @@
1
+ var ElasticsearchCoreModule_1;
2
+ import { __decorate, __metadata, __param } from "tslib";
3
+ import assert from 'node:assert';
4
+ import * as crypto from 'node:crypto';
5
+ import process from 'node:process';
6
+ import { clone } from '@jsopen/objects';
7
+ import { Inject, Logger } from '@nestjs/common';
8
+ import { ElasticsearchModule, ElasticsearchService } from '@nestjs/elasticsearch';
9
+ import * as colors from 'ansi-colors';
10
+ import { toBoolean, toInt } from 'putil-varhelpers';
11
+ import { ELASTICSEARCH_CONNECTION_OPTIONS, ELASTICSEARCH_MODULE_ID } from './constants.js';
12
+ const CLIENT_TOKEN = Symbol('CLIENT_TOKEN');
13
+ let ElasticsearchCoreModule = ElasticsearchCoreModule_1 = class ElasticsearchCoreModule {
14
+ /**
15
+ *
16
+ */
17
+ static forRoot(moduleOptions) {
18
+ const connectionOptions = this._readConnectionOptions(moduleOptions.useValue || {}, moduleOptions.envPrefix);
19
+ return this._createDynamicModule(moduleOptions, {
20
+ global: moduleOptions.global,
21
+ providers: [
22
+ {
23
+ provide: ELASTICSEARCH_CONNECTION_OPTIONS,
24
+ useValue: connectionOptions,
25
+ },
26
+ ],
27
+ });
28
+ }
29
+ /**
30
+ *
31
+ */
32
+ static forRootAsync(asyncOptions) {
33
+ assert.ok(asyncOptions.useFactory, 'useFactory is required');
34
+ return this._createDynamicModule(asyncOptions, {
35
+ global: asyncOptions.global,
36
+ providers: [
37
+ {
38
+ provide: ELASTICSEARCH_CONNECTION_OPTIONS,
39
+ inject: asyncOptions.inject,
40
+ useFactory: async (...args) => {
41
+ const opts = await asyncOptions.useFactory(...args);
42
+ return this._readConnectionOptions(opts, asyncOptions.envPrefix);
43
+ },
44
+ },
45
+ ],
46
+ });
47
+ }
48
+ static _createDynamicModule(opts, metadata) {
49
+ const token = opts.token ?? ElasticsearchService;
50
+ const logger = typeof opts.logger === 'string' ? new Logger(opts.logger) : opts.logger;
51
+ const exports = [ELASTICSEARCH_CONNECTION_OPTIONS, ...(metadata.exports ?? [])];
52
+ const providers = [
53
+ ...(metadata.providers ?? []),
54
+ {
55
+ provide: Logger,
56
+ useValue: logger,
57
+ },
58
+ {
59
+ provide: CLIENT_TOKEN,
60
+ useExisting: ElasticsearchService,
61
+ },
62
+ {
63
+ provide: ELASTICSEARCH_MODULE_ID,
64
+ useValue: crypto.randomUUID(),
65
+ },
66
+ ];
67
+ if (token !== ElasticsearchService) {
68
+ exports.push(token);
69
+ providers.push({
70
+ provide: token,
71
+ useExisting: ElasticsearchService,
72
+ });
73
+ }
74
+ class InnerProvidersModule {
75
+ }
76
+ return {
77
+ module: ElasticsearchCoreModule_1,
78
+ providers,
79
+ // global: true,
80
+ imports: [
81
+ ElasticsearchModule.registerAsync({
82
+ imports: [
83
+ {
84
+ module: InnerProvidersModule,
85
+ providers: metadata.providers,
86
+ exports: metadata.providers,
87
+ },
88
+ ],
89
+ inject: [ELASTICSEARCH_CONNECTION_OPTIONS],
90
+ useFactory: async (connectionOptions) => {
91
+ return connectionOptions;
92
+ },
93
+ }),
94
+ ],
95
+ exports,
96
+ };
97
+ }
98
+ static _readConnectionOptions(moduleOptions, prefix = 'ELASTIC_') {
99
+ const options = clone(moduleOptions);
100
+ const env = process.env;
101
+ options.node = options.node || env[prefix + 'NODE'];
102
+ if (options.node) {
103
+ if (typeof options.node === 'string' && options.node.includes(','))
104
+ options.node.split(/\s*,\s*/);
105
+ }
106
+ else {
107
+ options.nodes = options.nodes || env[prefix + 'NODES'];
108
+ if (options.nodes) {
109
+ if (typeof options.nodes === 'string' && options.nodes.includes(','))
110
+ options.nodes.split(/\s*,\s*/);
111
+ }
112
+ }
113
+ if (!(options.node || options.nodes))
114
+ options.node = 'http://localhost:9200';
115
+ options.maxRetries = options.maxRetries ?? toInt(env[prefix + 'MAX_RETRIES']);
116
+ options.requestTimeout = options.requestTimeout ?? toInt(env[prefix + 'REQUEST_TIMEOUT']);
117
+ options.pingTimeout = options.pingTimeout ?? toInt(env[prefix + 'PING_TIMEOUT']);
118
+ if (options.tls == null && toBoolean(env[prefix + 'TLS'])) {
119
+ options.tls = {
120
+ ca: [env[prefix + 'TLS_CA_CERT'] || ''],
121
+ cert: env[prefix + 'TLS_CERT_FILE'],
122
+ key: env[prefix + 'TLS_KEY_FILE'],
123
+ passphrase: env[prefix + 'TLS_KEY_PASSPHRASE'],
124
+ rejectUnauthorized: toBoolean(env[prefix + 'TLS_REJECT_UNAUTHORIZED']),
125
+ checkServerIdentity: (host, cert) => {
126
+ if (cert.subject.CN !== host) {
127
+ return new Error(`Certificate CN (${cert.subject.CN}) does not match host (${host})`);
128
+ }
129
+ },
130
+ };
131
+ }
132
+ options.name = options.name ?? env[prefix + 'NAME'];
133
+ if (!options.auth) {
134
+ if (env[prefix + 'AUTH_USERNAME']) {
135
+ options.auth = {
136
+ username: env[prefix + 'AUTH_USERNAME'],
137
+ password: env[prefix + 'AUTH_PASSWORD'] || '',
138
+ };
139
+ }
140
+ else if (env[prefix + 'AUTH_BEARER']) {
141
+ options.auth = {
142
+ bearer: env[prefix + 'AUTH_BEARER'],
143
+ };
144
+ }
145
+ else if (env[prefix + 'AUTH_API_KEY']) {
146
+ if (env[prefix + 'API_KEY_ID'])
147
+ options.auth = {
148
+ apiKey: {
149
+ id: env[prefix + 'API_KEY_ID'],
150
+ api_key: env[prefix + 'API_KEY'],
151
+ },
152
+ };
153
+ options.auth = {
154
+ apiKey: env[prefix + 'API_KEY'],
155
+ };
156
+ }
157
+ }
158
+ options.caFingerprint = options.caFingerprint ?? env[prefix + 'CA_FINGERPRINT'];
159
+ options.maxResponseSize = options.maxResponseSize ?? toInt(env[prefix + 'MAX_RESPONSE_SIZE']);
160
+ options.maxCompressedResponseSize =
161
+ options.maxCompressedResponseSize ?? toInt(env[prefix + 'MAX_COMPRESSED_RESPONSE_SIZE']);
162
+ return options;
163
+ }
164
+ /**
165
+ *
166
+ * @constructor
167
+ */
168
+ constructor(client, logger, connectionOptions) {
169
+ this.client = client;
170
+ this.logger = logger;
171
+ this.connectionOptions = connectionOptions;
172
+ }
173
+ async onApplicationBootstrap() {
174
+ if (this.logger) {
175
+ const options = this.connectionOptions;
176
+ const nodes = options.node || options.nodes;
177
+ this.logger.log(`Connecting to ElasticSearch at ${colors.blue(String(nodes))}`);
178
+ Logger.flush();
179
+ await this.client.ping({}).catch(e => {
180
+ this.logger.error('ElasticSearch connection failed: ' + e.message);
181
+ throw e;
182
+ });
183
+ }
184
+ }
185
+ onApplicationShutdown() {
186
+ return this.client.close();
187
+ }
188
+ };
189
+ ElasticsearchCoreModule = ElasticsearchCoreModule_1 = __decorate([
190
+ __param(0, Inject(CLIENT_TOKEN)),
191
+ __param(2, Inject(ELASTICSEARCH_CONNECTION_OPTIONS)),
192
+ __metadata("design:paramtypes", [ElasticsearchService,
193
+ Logger, Object])
194
+ ], ElasticsearchCoreModule);
195
+ export { ElasticsearchCoreModule };
@@ -0,0 +1,28 @@
1
+ import { ElasticsearchCoreModule } from './elasticsearch-core.module.js';
2
+ /**
3
+ * The ElasticsearchModule class is responsible for providing integration with Elasticsearch
4
+ * through dynamic module configurations. It allows synchronous and asynchronous setup of
5
+ * Elasticsearch configurations for use in a Node.js application.
6
+ */
7
+ export class ElasticsearchModule {
8
+ /**
9
+ * Configures and returns the dynamic module for the Elasticsearch integration.
10
+ *
11
+ */
12
+ static forRoot(options) {
13
+ return {
14
+ module: ElasticsearchModule,
15
+ imports: [ElasticsearchCoreModule.forRoot(options || {})],
16
+ };
17
+ }
18
+ /**
19
+ * Configures and returns the async dynamic module for the Elasticsearch integration.
20
+ *
21
+ */
22
+ static forRootAsync(options) {
23
+ return {
24
+ module: ElasticsearchModule,
25
+ imports: [ElasticsearchCoreModule.forRootAsync(options)],
26
+ };
27
+ }
28
+ }
package/esm/index.js ADDED
@@ -0,0 +1,4 @@
1
+ export * from './constants.js';
2
+ export * from './elasticsearch.module.js';
3
+ export * from './types.js';
4
+ export { ElasticsearchService } from '@nestjs/elasticsearch';
@@ -0,0 +1,3 @@
1
+ {
2
+ "type": "module"
3
+ }
package/esm/types.js ADDED
@@ -0,0 +1 @@
1
+ export {};
package/package.json ADDED
@@ -0,0 +1,56 @@
1
+ {
2
+ "name": "@xnestjs/elasticsearch",
3
+ "version": "1.3.0",
4
+ "description": "NestJS extension library for ElasticSearch",
5
+ "author": "Panates",
6
+ "license": "MIT",
7
+ "dependencies": {
8
+ "@jsopen/objects": "^1.5.2",
9
+ "ansi-colors": "^4.1.3",
10
+ "putil-varhelpers": "^1.6.5",
11
+ "tslib": "^2.8.1"
12
+ },
13
+ "peerDependencies": {
14
+ "@nestjs/common": "^10.0.0 || ^11.0.0",
15
+ "@nestjs/core": "^10.0.0 || ^11.0.0",
16
+ "@nestjs/elasticsearch": "^10.0.0 || ^11.0.0",
17
+ "@elastic/elasticsearch": "^7.4.0 || ^8.0.0"
18
+ },
19
+ "type": "module",
20
+ "exports": {
21
+ ".": {
22
+ "import": {
23
+ "types": "./types/index.d.ts",
24
+ "default": "./esm/index.js"
25
+ },
26
+ "require": {
27
+ "types": "./types/index.d.cts",
28
+ "default": "./cjs/index.js"
29
+ },
30
+ "default": "./esm/index.js"
31
+ },
32
+ "./package.json": "./package.json"
33
+ },
34
+ "main": "./cjs/index.js",
35
+ "module": "./esm/index.js",
36
+ "types": "./types/index.d.ts",
37
+ "repository": {
38
+ "registry": "https://github.com/panates/xnestjs.git",
39
+ "directory": "packages/elasticsearch"
40
+ },
41
+ "engines": {
42
+ "node": ">=16.0",
43
+ "npm": ">=7.0.0"
44
+ },
45
+ "files": [
46
+ "cjs/",
47
+ "esm/",
48
+ "types/",
49
+ "LICENSE",
50
+ "README.md"
51
+ ],
52
+ "keywords": [
53
+ "nestjs",
54
+ "elasticsearch"
55
+ ]
56
+ }
@@ -0,0 +1,2 @@
1
+ export declare const ELASTICSEARCH_CONNECTION_OPTIONS: unique symbol;
2
+ export declare const ELASTICSEARCH_MODULE_ID: unique symbol;
@@ -0,0 +1,25 @@
1
+ import { DynamicModule, Logger, OnApplicationBootstrap, OnApplicationShutdown } from '@nestjs/common';
2
+ import { ElasticsearchService } from '@nestjs/elasticsearch';
3
+ import type { ElasticsearchConnectionOptions, ElasticsearchModuleAsyncOptions, ElasticsearchModuleOptions } from './types.js';
4
+ export declare class ElasticsearchCoreModule implements OnApplicationShutdown, OnApplicationBootstrap {
5
+ protected client: ElasticsearchService;
6
+ private logger;
7
+ private connectionOptions;
8
+ /**
9
+ *
10
+ */
11
+ static forRoot(moduleOptions: ElasticsearchModuleOptions): DynamicModule;
12
+ /**
13
+ *
14
+ */
15
+ static forRootAsync(asyncOptions: ElasticsearchModuleAsyncOptions): DynamicModule;
16
+ private static _createDynamicModule;
17
+ private static _readConnectionOptions;
18
+ /**
19
+ *
20
+ * @constructor
21
+ */
22
+ constructor(client: ElasticsearchService, logger: Logger, connectionOptions: ElasticsearchConnectionOptions);
23
+ onApplicationBootstrap(): Promise<void>;
24
+ onApplicationShutdown(): Promise<void>;
25
+ }
@@ -0,0 +1,19 @@
1
+ import type { DynamicModule } from '@nestjs/common';
2
+ import type { ElasticsearchModuleAsyncOptions, ElasticsearchModuleOptions } from './types';
3
+ /**
4
+ * The ElasticsearchModule class is responsible for providing integration with Elasticsearch
5
+ * through dynamic module configurations. It allows synchronous and asynchronous setup of
6
+ * Elasticsearch configurations for use in a Node.js application.
7
+ */
8
+ export declare class ElasticsearchModule {
9
+ /**
10
+ * Configures and returns the dynamic module for the Elasticsearch integration.
11
+ *
12
+ */
13
+ static forRoot(options?: ElasticsearchModuleOptions): DynamicModule;
14
+ /**
15
+ * Configures and returns the async dynamic module for the Elasticsearch integration.
16
+ *
17
+ */
18
+ static forRootAsync(options: ElasticsearchModuleAsyncOptions): DynamicModule;
19
+ }
@@ -0,0 +1,4 @@
1
+ export * from './constants.js';
2
+ export * from './elasticsearch.module.js';
3
+ export * from './types.js';
4
+ export { ElasticsearchService } from '@nestjs/elasticsearch';
@@ -0,0 +1,4 @@
1
+ export * from './constants.js';
2
+ export * from './elasticsearch.module.js';
3
+ export * from './types.js';
4
+ export { ElasticsearchService } from '@nestjs/elasticsearch';
@@ -0,0 +1,20 @@
1
+ import type { ClientOptions } from '@elastic/elasticsearch';
2
+ import type { Logger } from '@nestjs/common';
3
+ import type { ModuleMetadata } from '@nestjs/common/interfaces';
4
+ import type { InjectionToken } from '@nestjs/common/interfaces/modules/injection-token.interface';
5
+ export interface ElasticsearchConnectionOptions extends ClientOptions {
6
+ }
7
+ interface BaseModuleOptions {
8
+ token?: InjectionToken;
9
+ envPrefix?: string;
10
+ logger?: Logger | string;
11
+ global?: boolean;
12
+ }
13
+ export interface ElasticsearchModuleOptions extends BaseModuleOptions {
14
+ useValue?: ElasticsearchConnectionOptions;
15
+ }
16
+ export interface ElasticsearchModuleAsyncOptions extends BaseModuleOptions, Pick<ModuleMetadata, 'imports'> {
17
+ inject?: InjectionToken[];
18
+ useFactory: (...args: any[]) => Promise<ElasticsearchConnectionOptions> | ElasticsearchConnectionOptions;
19
+ }
20
+ export {};