@sap/cds-dk
Version:
Command line client and development toolkit for the SAP Cloud Application Programming Model
90 lines (80 loc) • 3.25 kB
JavaScript
const cds = require('../cds');
const { ParamCollection } = require('./params');
const AuthManager = require('./auth_manager');
require('../util/axios').pruneErrors();
const { getMessage } = require('./util/logging');
const { capitalize } = require('./util/strings');
const { handleHttpError } = require('./util/errors');
const DEBUG = cds.debug('cli');
const COMMANDS = {
subscribe: 'to',
upgrade: 'at',
unsubscribe: 'from'
};
module.exports = class TenantAction {
// TODO JSDoc
/**
* @param command {string} the command to execute: 'subscribe', 'upgrade' or 'unsubscribe'
*/
constructor(command) {
if (!(command in COMMANDS)) {
throw `invalid command: ${command}`;
}
this.command = command;
this.gerund = command.replace(/e$/, 'ing');
this.preposition = COMMANDS[command];
}
async run(paramValues, { tenant, local } = {}) {
let params = new ParamCollection(paramValues);
params.set('skipToken', true); // Token would have insufficient scopes for this command.
if (local) {
// Connect to locally-served MTXS
await this.runWithServer(params, tenant);
} else {
// Connect to running MTXS server
params = await AuthManager.login(params.toEntries());
await this.runClientOnly(params, tenant);
}
console.log(`${capitalize(this.command)} successful.`);
}
async runClientOnly(params, tenant) {
console.log(capitalize(this.gerund), { tenant }, this.preposition, { url: params.get('appUrl') });
const url = `${params.get('appUrl')}/-/cds/deployment/${this.command}`;
DEBUG?.(`Sending request to ${url}`);
const body = params.get('body');
let parsedBody;
if (body) {
try {
parsedBody = JSON.parse(body)
} catch (error) {
throw getMessage('Invalid subscription body', { error, command: this.command });
}
}
try {
await require('axios').post(url, { tenant, metadata: parsedBody, options: parsedBody }, params.get('reqAuth'));
} catch (error) {
handleHttpError(error, params, { url });
}
}
async runWithServer(params, tenant) {
const libId = '@sap/cds-mtxs/bin/cds-mtx';
let libPath;
try {
libPath = require.resolve(libId, { paths: [process.cwd()] });
DEBUG?.(`Using local @sap/cds-mtxs from ${libPath}`);
} catch (error) {
try {
libPath = require.resolve(libId);
DEBUG?.(`Using cds-mtxs from ${libPath}`);
} catch (error) {
throw getMessage('@sap/cds-mtxs not found or outdated. Have you changed into the directory of your SaaS app? If so, please upgrade to @sap/cds-mtxs@>=1.7.0', { error, command: this.command });
}
}
const { cds_mtx } = require(libPath);
if (!cds_mtx) {
throw '@sap/cds-mtxs outdated. Please upgrade to @sap/cds-mtxs@>=1.7.0 and re-run this command.';
}
const body = params.get('body')
return cds_mtx(this.command, tenant, body);
}
}