UNPKG

denwa-nest-shared

Version:

Shared NestJS module for DTO validation, RBAC, TypeORM query building, and OpenAPI client

99 lines • 3.54 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.OpenSearchCore = void 0; class OpenSearchCore { client; enabled; constructor(client, enabled) { this.client = client; this.enabled = enabled; } async ensureIndex(index) { if (!this.enabled || !this.client) return; try { const exists = await this.client.indices.exists({ index }); if (!exists.body) { await this.client.indices.create({ index, body: { settings: { number_of_shards: 1, number_of_replicas: 0 }, mappings: { properties: { id: { type: 'keyword' }, nameRU: { type: 'text', analyzer: 'russian' }, nameEN: { type: 'text', analyzer: 'english' }, descriptionRU: { type: 'text', analyzer: 'russian' }, descriptionEN: { type: 'text', analyzer: 'english' }, createdAt: { type: 'date' }, updatedAt: { type: 'date' }, }, }, }, }); } } catch (error) { console.error(`Failed to ensure index '${index}': ${error.message}`); } } async indexDocument(index, id, body) { if (!this.enabled || !this.client) return; try { await this.client.index({ index, id, body, refresh: 'true' }); } catch (error) { console.error(`Failed to index document '${id}' in '${index}': ${error.message}`); } } async removeDocument(index, id) { if (!this.enabled || !this.client) return; try { await this.client.delete({ index, id, refresh: 'true' }); } catch (error) { console.error(`Failed to remove document '${id}' from '${index}': ${error.message}`); } } async search(index, query, fields, page = 1, limit = 20) { if (!this.enabled || !this.client) { return { data: [], total: 0, page, limit }; } try { const from = (page - 1) * limit; const result = await this.client.search({ index, from, size: limit, body: { query: { multi_match: { query, fields, type: 'best_fields', fuzziness: 'AUTO', }, }, }, }); const totalHits = typeof result.body.hits.total === 'number' ? result.body.hits.total : (result.body.hits.total?.value ?? 0); const hits = result.body.hits.hits ?? []; return { data: hits.map((h) => h._source ?? {}), total: totalHits, page, limit, }; } catch (error) { console.error(`Search failed on '${index}': ${error.message}`); return { data: [], total: 0, page, limit }; } } } exports.OpenSearchCore = OpenSearchCore; //# sourceMappingURL=opensearch-core.js.map