UNPKG

@vara/custom-logic-sdk

Version:

Server Side JavaScript SDK for Custom Business Logic

62 lines (47 loc) 2.42 kB
/** * Created by stevenchin on 2/1/17. */ const _ = require('lodash'); const clFnRegistry = require('../services/fn-registry'); const customError = require('../services/custom-error'); const fnExecutorSvc = require('../services/fn-executor-svc'); const ApplicationErrors = require('../constants/application-errors.json'); const logSvc = require('../services/log-svc'); const CUSTOM_LOGIC = require('../constants/constants').CUSTOM_LOGIC; const { ResourceNotFoundError, InternalError } = ApplicationErrors; async function clFnExecutor(req, res, next) { const logPrefix = 'RouteHandler#clFnExecutor'; const clFunctionName = _.get(req, 'params.name'); const clFunction = clFnRegistry.getAPIResponder(clFunctionName); const requestedClProtocolVersion = req.get(CUSTOM_LOGIC.PROTOCOL.PROTOCOL_VERSION_REQ_HEADER) || CUSTOM_LOGIC.PROTOCOL.VERSIONS.LATEST; const logCtx = { clFunctionName, registeredClProtocolVersion: _.get(clFunction, 'config.clProtocolVersion'), requestedClProtocolVersion, }; // To execute the custom logic function: // 1) it must exist in the registry // 2) its protocol version must match the current protocol version or the one sent by the platform if (!clFunction || _.get(clFunction, 'config.clProtocolVersion') !== requestedClProtocolVersion) { const resourceNotFoundErr = customError( ResourceNotFoundError.name, `Custom Logic Function: ${clFunctionName} with protocol version: ${requestedClProtocolVersion} was not found`); logSvc.logWarning(resourceNotFoundErr, logCtx, logPrefix); return next(resourceNotFoundErr); } try { // Attempt to build the necessary inputs for the custom logic function based on the protocol version const { context, done } = fnExecutorSvc.buildClFnParams(requestedClProtocolVersion, req, res, next); return await fnExecutorSvc.execHandler(clFunction.handler, context, done); } catch (err) { // handle cases where a protocol handler could not be found for the custom logic protocol specified if (err.name === ResourceNotFoundError.name) { logSvc.logWarning(err, logCtx, logPrefix); return next(err); } const internalErr = customError(InternalError.name, null, { innerError: err }); logSvc.logError(internalErr, logCtx, logPrefix, `Custom Logic Function: ${clFunctionName} failed;`); return next(internalErr); } } module.exports = clFnExecutor;