@sap-cloud-sdk/resilience
Version:
SAP Cloud SDK for JavaScript resilience
35 lines • 1.68 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.executeWithMiddleware = executeWithMiddleware;
/**
* Helper function to join a list of middlewares given an initial input.
* @param middlewares - Middlewares to be layered around the function.
* @param context - Context for the middleware execution.
* @param fn - Function around which the middlewares are added.
* @returns Function with middlewares layered around it.
* @internal
*/
function executeWithMiddleware(middlewares, { fn, context, fnArgument }) {
if (!middlewares?.length) {
return fn(fnArgument);
}
const initial = { context, fn };
const functionWithMiddlewares = addMiddlewaresToInitialFunction(middlewares, initial);
return functionWithMiddlewares(fnArgument);
}
/**
* This functions adds the middlewares to the initial functions.
* You start with a function (axios request function) and add a timeout, circuit-breaker etc..
* The result is new a function containing a timeout, circuit-breaker etc..
* Note that the actual function is not executed.
* @param middlewares - Middlewares added to the function. Added from right to function.
* @param initial - Initial function and context.
* @returns The function with the middlewares added.
*/
function addMiddlewaresToInitialFunction(middlewares, initial) {
const { context } = initial;
// Reduce right is in line with the composition operator [g,f] relates g o f means g after f.
const functionWithMiddlewares = middlewares.reduceRight((prev, curr) => ({ fn: curr(prev), context }), initial);
return functionWithMiddlewares.fn;
}
//# sourceMappingURL=middleware.js.map