UNPKG

@opra/elastic

Version:

Opra Elastic Search adapter package

61 lines (60 loc) 1.8 kB
import { ServiceBase } from '@opra/core'; /** * Class representing a ElasticSearch service for interacting with a collection. * @extends ServiceBase * @template T - The type of the documents in the collection. */ export class ElasticService extends ServiceBase { /** * Constructs a new instance * * @param [options] - The options for the service * @constructor */ constructor(options) { super(); this.interceptor = options?.interceptor; this.client = options?.client; this.onError = options?.onError; } /** * Retrieves the ElasticSearch client. * * @protected * * @throws {Error} If the context or client is not set. */ getClient() { // @ts-ignore const db = typeof this.client === 'function' ? this.client(this) : this.client; if (!db) throw new Error(`Client not set!`); return db; } async _executeCommand(command, commandFn) { let proto; const next = async () => { proto = proto ? Object.getPrototypeOf(proto) : this; while (proto) { if (proto.interceptor && Object.prototype.hasOwnProperty.call(proto, 'interceptor')) { return await proto.interceptor.call(this, next, command, this); } proto = Object.getPrototypeOf(proto); if (!(proto instanceof ElasticService)) break; } return commandFn(); }; try { return await next(); } catch (e) { Error.captureStackTrace(e, this._executeCommand); await this.onError?.(e, this); throw e; } } }