/** * Compose `middleware` returning * a fully valid middleware comprised * of all those which are passed. * * @param {Array}middleware * @return {Function} * @api public */
functioncompose(middleware) { if (!Array.isArray(middleware)) thrownewTypeError('Middleware stack must be an array!'); for (const fn of middleware) { if (typeof fn !== 'function') thrownewTypeError('Middleware must be composed of functions!'); }
returnfunction (context, next) { // last called middleware # let index = -1; return dispatch(0); functiondispatch(i) { if (i <= index) returnPromise.reject(newError('next() called multiple times')); index = i; let fn = middleware[i]; if (i === middleware.length) fn = next; if (!fn) returnPromise.resolve(); try { returnPromise.resolve(fn(context, dispatch.bind(null, i + 1))); } catch (err) { returnPromise.reject(err); } } }; }
const compose = (middleware) => { if (!Array.isArray(middleware)) thrownewTypeError('Middleware stack must be an array!'); for (const fn of middleware) { if (typeof fn !== 'function') thrownewTypeError('Middleware must be composed of functions!'); }
return(next) => { // last called middleware # let index = -1; const dispatch = (i: number) => (...args) => { if (i <= index) returnPromise.reject(newError('next() called multiple times')); index = i; const fn = middleware[i]; if (i === middleware.length) { if (next) { returnPromise.resolve(next(...args)); } } if (!fn) returnPromise.resolve(); try { returnPromise.resolve(fn(dispatch(i + 1))(...args)); } catch (err) { returnPromise.reject(err); } }; return dispatch(0); }; };
const compose: MiddlewareCompose<AnyFunction> = <T extends AnyFunction>( middleware: MiddlewareFunction<T>[], ): ((next: NextFunction<T>) => NextFunction<T>) => { if (!Array.isArray(middleware)) throw new TypeError('Middleware stack must be an array!'); for (const fn of middleware) { if (typeof fn !== 'function') throw new TypeError('Middleware must be composed of functions!'); }
return (next: NextFunction<T>) => { // last called middleware # let index = -1; const dispatch: (i: number) => NextFunction<T> = (i: number) => (...args: Parameters<T>): ReturnType<T> => { if (i <= index) return Promise.reject(new Error('next() called multiple times')) as ReturnType<T>; index = i; const fn = middleware[i]; if (i === middleware.length) { if (next) { return Promise.resolve(next(...args)) as ReturnType<T>; } } if (!fn) return Promise.resolve() as ReturnType<T>; try { return Promise.resolve(fn(dispatch(i + 1))(...args)) as ReturnType<T>; } catch (err) { return Promise.reject(err) as ReturnType<T>; } }; return dispatch(0); }; };