UNPKG

@akala/core

Version:
81 lines 2.84 kB
import { convertToErrorMiddleware, isStandardMiddleware, isErrorMiddleware, NotHandled } from './shared.js'; /** * MiddlewareIndexedAsync class that implements MiddlewareAsync and ExtendableIndexedMiddleware. * @template T - The type of the arguments. * @template TMiddleware - The type of the middleware. */ export class MiddlewareIndexedAsync { getIndexKey; name; _delegate; /** * Constructor for MiddlewareIndexedAsync. * @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 of the index. * @returns {string[]} The keys of the index. */ 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 instance of MiddlewareIndexedAsync. */ useError(handler) { return this.useMiddleware('', convertToErrorMiddleware(handler)); } /** * Process the request. * @template X - The type of the return value. * @param {...T} req - The request arguments. * @returns {Promise<X>} The result of the processing. */ process(...req) { return this.handle(...req).then(x => typeof x !== 'undefined' ? Promise.reject(x) : Promise.resolve(x), x => Promise.resolve(x)); } /** * Handle an error. * @param {Error|OptionsResponse} error - The error to handle. * @param {...T} req - The request arguments. * @returns {MiddlewarePromise} The result of the error handling. */ async handleError(error, ...req) { if (isErrorMiddleware(this.index[''])) return this.index[''].handleError(error, ...req); return error; } /** * Handle the request. * @param {...T} req - The request arguments. * @returns {MiddlewarePromise} 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 NotHandled; const middleware = this.index[key]; if (isStandardMiddleware(middleware)) return middleware.handle(...req).then(e => (typeof e === 'undefined') && this._delegate ? this._delegate.handle(...req) : e); return NotHandled; } } //# sourceMappingURL=indexed-async.js.map