UNPKG

@akala/core

Version:
86 lines 2.65 kB
import { process, convertToErrorMiddleware, isStandardMiddleware, isErrorMiddleware } from './shared.js'; /** * MiddlewareIndexed class that implements Middleware. * @template T * @template TMiddleware * @template TSpecialNextParam */ export class MiddlewareIndexed { getIndexKey; name; _delegate; /** * Constructor for MiddlewareIndexed. * @param {function} getIndexKey - Function to get the index key. * @param {string} [name] - Optional name for the middleware. */ constructor(getIndexKey, name) { this.getIndexKey = getIndexKey; this.name = name; } /** * Get the keys from the index. * @returns {string[]} Array of keys. */ getKeys() { return Object.keys(this.index).filter(v => v !== ''); } index = {}; useMiddleware(key, middleware) { if (key === null) this._delegate = middleware; else this.index[key] = middleware; return this; } /** * Use an error handler. * @param {function} handler - The error handler function. * @returns {this} The current instance. */ useError(handler) { return this.useMiddleware('', convertToErrorMiddleware(handler)); } /** * Process the request. * @template X * @param {...T} req - The request parameters. * @returns {X} The result of the process. */ process(...req) { return process(this, ...req); } /** * Handle an error. * @param {Error|OptionsResponse} error - The error to handle. * @param {...T} req - The request parameters. * @returns {MiddlewareResult<TSpecialNextParam>} The result of the error handling. */ handleError(error, ...req) { if (isErrorMiddleware(this.index[''])) return this.index[''].handleError(error, ...req); return error; } /** * Handle the request. * @param {...T} req - The request parameters. * @returns {MiddlewareResult<TSpecialNextParam>} The result of the handling. */ handle(...req) { var key = this.getIndexKey(...req); if (!key || !this.index[key]) if (this._delegate) return this._delegate.handle(...req); else return; const middleware = this.index[key]; if (isStandardMiddleware(middleware)) { const e = middleware.handle(...req); if (typeof e === 'undefined' && this._delegate) return this._delegate.handle(...req); return e; } return; } } //# sourceMappingURL=indexed-sync.js.map