/* * Copyright Elasticsearch B.V. and contributors * SPDX-License-Identifier: Apache-2.0 */ import { ElasticsearchClientError } from '../errors.js'; export class MiddlewareException extends Error { constructor(message, options) { super(message, options); this.name = 'MiddlewareException'; } } export class MiddlewareEngine { constructor() { Object.defineProperty(this, "middleware", { enumerable: true, configurable: true, writable: true, value: [] }); } register(middleware) { this.middleware.push(middleware); this.middleware.sort((a, b) => { var _a, _b; return ((_a = a.priority) !== null && _a !== void 0 ? _a : 100) - ((_b = b.priority) !== null && _b !== void 0 ? _b : 100); }); } /** * Wraps `run` (the request, including all retries) in the `around` handlers as * an onion: highest priority (lowest number) is outermost. Errors propagate as-is. */ async run(context, run) { let next = run; for (let i = this.middleware.length - 1; i >= 0; i--) { const around = this.middleware[i].around; if (around == null) continue; const inner = next; next = async () => await around(context, inner); } return await next(); } /** * Runs every `onResponse` handler in priority order on each HTTP response * within the retry loop. A handler returning `{ continue: false }` stops the rest. */ executeOnResponse(context, result) { var _a; for (const middleware of this.middleware) { if (middleware.onResponse == null) continue; try { if (((_a = middleware.onResponse(context, result)) === null || _a === void 0 ? void 0 : _a.continue) === false) return; } catch (error) { if (error instanceof ElasticsearchClientError) throw error; throw new MiddlewareException(`Middleware ${middleware.name} failed in onResponse`, { cause: error }); } } } } //# sourceMappingURL=MiddlewareEngine.js.map