@sap/low-code-event-handler
Version:
The generic event handlers for LCAP
160 lines (145 loc) • 5.57 kB
JavaScript
const cds = require('@sap/cds');
const xsenv = require('@sap/xsenv');
const LOG = cds.log('lcap-mtx')
const cfenv = require('cfenv');
const appEnv = cfenv.getAppEnv();
const httpClient = require('@sap-cloud-sdk/http-client');
xsenv.loadEnv();
const cfDestinationName = process.env.CF_API_DEST;
LOG.info(`The CF API destination name is: ${cfDestinationName}`);
async function executeHttpRequest(options) {
try {
return await httpClient.executeHttpRequest({ destinationName: cfDestinationName }, options);
} catch (err) {
LOG.error(err.stack);
return err.message;
}
}
async function getCFInfo(appname) {
const currentAppUri = appEnv.app.application_uris[0];
const domainStartIndex = currentAppUri.indexOf(".") + 1;
const domainName = currentAppUri.slice(domainStartIndex)
const res1 = await executeHttpRequest({
method: 'GET',
url: `/v3/apps?organization_guids=${appEnv.app.organization_id}&space_guids=${appEnv.app.space_id}&names=${appname}`
});
const res2 = await executeHttpRequest({
method: 'GET',
url: `/v3/domains?names=${domainName}`
});
return {
'app_id': res1.data.resources[0].guid,
'domain_id': res2.data.resources[0].guid
};
}
async function createRoute(subscribedSubdomain, appname) {
try {
const CFInfo = await getCFInfo(appname);
LOG.info(CFInfo);
const res1 = await executeHttpRequest({
method: 'POST',
url: '/v3/routes',
data: {
'host': `${subscribedSubdomain}-${process.env.APP_URI.split('.')[0]}`,
'relationships': {
'space': {
'data': {
'guid': appEnv.app.space_id
}
},
'domain': {
'data': {
'guid': CFInfo.domain_id
}
}
}
},
});
const res2 = await executeHttpRequest({
method: 'POST',
url: `/v3/routes/${res1.data.guid}/destinations`,
data: {
'destinations': [{
'app': {
'guid': CFInfo.app_id
}
}]
},
});
LOG.info(`Route created for ${subscribedSubdomain}`);
return true; // Route created successfully
} catch (error) {
LOG.error(`Route creation failed: ${error.message}`);
return false; // Route creation failed
}
}
async function deleteRoute(subscribedSubdomain, appname) {
try {
const CFInfo = await getCFInfo(appname);
const res1 = await executeHttpRequest({
method: 'GET',
url: `/v3/apps/${CFInfo.app_id}/routes?hosts=${subscribedSubdomain}-${process.env.APP_URI.split('.')[0]}`
});
if (res1.data.pagination.total_results === 1) {
const res2 = await executeHttpRequest({
method: 'DELETE',
url: `/v3/routes/${res1.data.resources[0].guid}`
});
LOG.info(`Route deleted for ${subscribedSubdomain}`);
return true; // Route deleted successfully
} else {
LOG.info(`Route not found for ${subscribedSubdomain}`);
return false; // Route not found
}
} catch (error) {
LOG.error(`Route deletion failed: ${error.message}`);
return false; // Route deletion failed
}
}
async function handleTenantUpdate(req, next, action) {
LOG.info(`Update tenant request data: ${req.data}`);
LOG.info(`Update tenant request: ${req}`);
const tenantURL = `${process.env.APP_PROTOCOL}://${req.data.subscribedSubdomain}-${process.env.APP_URI}`;
LOG.info(`Subscribe: ${req.data.subscribedSubdomain}, ${req.data.subscribedTenantId}, ${tenantURL}`);
await next();
const services = xsenv.getServices({
registry: { label: 'saas-registry' }
});
LOG.info(`services.registry.appName: ${services.registry.appName}`);
const myAppName = services.registry.appName.split("-")[0];
LOG.info(`myAppName: ${myAppName}`);
let actionResult = false;
try {
actionResult = await action(req.data.subscribedSubdomain, myAppName);
} catch (error) {
LOG.error(`Route creation failed: ${error.message}`);
}
return actionResult; // Return true if route creation was successful, false otherwise
}
function initRoute() {
LOG.info("====mtx.route.init===");
cds.on('served', async () => {
const { 'cds.xt.SaasProvisioningService': provisioning } = cds.services
await provisioning.prepend(() => {
provisioning.on('UPDATE', 'tenant', async (req, next) => {
return await handleTenantUpdate(req, next, createRoute);
});
provisioning.on('DELETE', 'tenant', async (req, next) => {
return await handleTenantUpdate(req, next, deleteRoute);
});
provisioning.on('dependencies', async (req, next) => {
await next();
const services = xsenv.getServices({
dest: { label: 'destination' }
});
let dependencies = [
{
xsappname: services.dest.xsappname
}
];
return dependencies;
});
});
});
}
exports.initRoute = initRoute;