@vara/custom-logic-sdk
Version:
Server Side JavaScript SDK for Custom Business Logic
95 lines (77 loc) • 3.08 kB
JavaScript
/**
* Created by stevenchin on 2/3/17.
*/
const _ = require('lodash');
const constants = require('../../constants/constants');
const url = require('url');
const { VERSIONS: PROTOCOL_VERSIONS } = constants.CUSTOM_LOGIC.PROTOCOL;
const { POST_HOOK, PRE_HOOK } = constants.CUSTOM_LOGIC.FUNCTIONS.TYPES;
/**
* Ensure the correct body is returned for the context object based on the custom logic function being executed.
* The response body should be returned for postHooks and the request body should be returned for standalone functions and preHooks
* @param clFunctionType {String}
* @param req {Object}
* @returns {*}
*/
function getContextBodyForClFunction(clFunctionType, req) {
if (clFunctionType === POST_HOOK) return _.get(req, 'body.response.body');
return _.get(req, 'body.request.body');
}
function buildClHandlerContext(req, res) {
const etxContext = _.get(req, 'body.context', {});
const etxRequestInfo = _.get(req, 'body.request', {});
const etxResponseInfo = _.get(req, 'body.response', {});
const context = {
// include original etx request for debugging
_etxPayload: req.body,
_req: req,
_res: res,
appId: _.get(etxContext, 'appId'),
clientKey: _.get(etxContext, 'clientKey'),
accessToken: _.get(etxContext, 'accessToken'),
user: _.get(etxContext, 'user'),
userRoles: _.get(etxContext, 'userRoles'),
body: getContextBodyForClFunction(_.get(req, 'body.type'), req),
requestInfo: etxRequestInfo,
responseInfo: etxResponseInfo,
requestContext: etxContext,
metadata: {
fnType: _.get(req, 'body.type'),
executionMode: _.get(req, 'body.executionMode'),
modelMethod: _.get(req, 'body.modelMethod'),
modelName: _.get(req, 'body.modelName'),
},
};
if (_.get(req, 'body.standaloneFn')) {
context.metadata.standaloneFnName = _.get(req, 'body.standaloneFn');
}
// all this stuff should come pre-parsed from the server in the future
if (context.metadata.fnType === PRE_HOOK) {
// extract method and path that triggered the pre-hook
context.metadata.method = context.requestInfo.method;
const urlPath = url.parse(context.requestInfo.url).pathname;
context.metadata.urlPath = urlPath;
// parse out /data/class/:name for custom objects
let match = urlPath.match(/data\/class\/([a-zA-Z]+)/);
if (match) {
context.metadata.className = `custom.${match[1]}`;
}
// parse out /:name for built-in objects -- also supports /data/:name for the future
match = !match && (urlPath.match(/v1\/data\/([a-zA-Z]+)/) || urlPath.match(/v1\/([a-zA-Z]+)/));
if (match) {
context.metadata.className = match[1];
}
}
// set customState for hooks (standalone functions don't have custom state)
const isHook = context.metadata.fnType === PRE_HOOK || context.metadata.fnType === POST_HOOK;
if (isHook) {
context.requestContext.customState = context.requestContext.customState;
}
return context;
}
module.exports = {
handler: {
buildClHandlerContext,
},
version: PROTOCOL_VERSIONS.V_1_0,
};