@waves/node-state
Version:
50 lines • 2.35 kB
JavaScript
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.middlewareWithContext = void 0;
/**
* This symbol definition is used to determine whether the last argument
* passed into a middleware is already a defined `next` call.
*
* This allows for `compose(mw1, compose(mw2, mw3))` to work as intended.
*/
const isNext = Symbol('isNext');
/**
* `middlewareWithContext` is variadic and takes middlewares as input.
* It returns a variadic function which is invoked with context(s) and then executes
* the middleware, currently `left-to-right`, returning a new `async` function.
*/
exports.middlewareWithContext = (...mw) => function (...args) {
return __awaiter(this, void 0, void 0, function* () {
/**
* The last `next` in the chain, should either call the `next` handler
* passed via `args` (denoting a continuation into another composition),
* or do a no-op.
*/
const nxt = args[args.length - 1][isNext] ? args.pop() : () => {
};
/**
* `await` execution of all the middleware provided, by reducing each
* supplied middleware and wrapping each function execution.
*/
yield mw.reduceRight((next, curr) => function () {
return __awaiter(this, void 0, void 0, function* () {
/**
* Decorate each `next` handler with our `isNext` symbol to facilitate
* composition of compositions.
*/
next[isNext] = true;
yield curr(...args.concat(next));
});
}, nxt)();
});
};
//# sourceMappingURL=middleware.js.map
;