@sap/low-code-event-handler
Version:
The generic event handlers for LCAP
101 lines (92 loc) • 2.95 kB
JavaScript
const path = require('path');
const fs = require('fs');
const cds = require('@sap/cds');
const APPLOGIC_ANNOTATION = '@applicationLogic';
const APPLOGIC_PATH = 'srv/code';
const CDS_APPSERVICE_CONFIG_NAME = 'app-service';
const CDS_APPLOGIC_CONFIG_PATH_NAME = 'app-logic-path';
class AppLogicHandler {
static async beforeEventHandler(service, request) {
return _execAppLogicAsync(service, Object.assign({
phase: 'before'
}, request), {
request
});
}
static async onEventHandler(service, request, next) {
return _execAppLogicAsync(service, Object.assign({
phase: 'on'
}, request), {
request, next
});
}
static async afterEventHandler(service, results, request) {
return _execAppLogicAsync(service, Object.assign({
phase: 'after'
}, request), {
results, request
});
}
}
async function _execAppLogicAsync(service, eventContext, appLogicContext) {
const matchedAppLogics = _findAppLogics(service, eventContext);
if (matchedAppLogics && matchedAppLogics.length > 0) {
const promises = [];
matchedAppLogics.forEach(appLogicConfig => {
try {
const appLogicPath = _getLogicFilePath(appLogicConfig.name);
if (appLogicPath && fs.existsSync(appLogicPath)) {
const appLogic = require(appLogicPath);
promises.push(appLogic(appLogicContext));
} else {
console.error('[lcap] Not exists application logic file path: ' + appLogicPath);
}
} catch (error) {
console.error(error.message);
console.debug(error);
}
});
return await Promise.all(promises).then(results => {
// console.debug(results);
return results;
}).catch(error => {
console.error(error.message);
console.debug(error);
throw error;
});
}
}
function _findAppLogics(service, eventContext) {
let target;
if (eventContext.target) {
target = eventContext.target;
} else {
const actionName = `${service.name}.${eventContext.event}`;
target = service.model.definitions[actionName];
}
if (!target) {
console.error('[lcap] Failed to find the context target.');
return [];
}
const appLogicConfigs = target[APPLOGIC_ANNOTATION];
if (!appLogicConfigs) {
return [];
} else {
return appLogicConfigs.filter(config => {
return config.events && config.events.find(eventConfig => {
return eventConfig.phase === eventContext.phase && eventConfig.name === eventContext.event;
});
});
}
}
function _getLogicFilePath(fileName) {
if (fileName) {
const appLogicPath = APPLOGIC_PATH;
const configName = cds.env.requires[CDS_APPSERVICE_CONFIG_NAME];
if (configName && configName[CDS_APPLOGIC_CONFIG_PATH_NAME]) {
appLogicPath = configName[CDS_APPLOGIC_CONFIG_PATH_NAME];
}
return path.join(cds.env._home, appLogicPath, fileName) + '.js';
}
}
module.exports = AppLogicHandler;