UNPKG

@axway/axway-central-cli

Version:

Manage APIs, services and publish to the Amplify Marketplace

196 lines (187 loc) 8.05 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.deleteCmd = void 0; var _chalk = _interopRequireDefault(require("chalk")); var _snooplogg = _interopRequireDefault(require("snooplogg")); var _ApiServerClient = require("../../common/ApiServerClient"); var _basicPrompts = require("../../common/basicPrompts"); var _DefinitionsManager = require("../../common/DefinitionsManager"); var _Renderer = _interopRequireDefault(require("../../common/Renderer")); var _types = require("../../common/types"); var _utils = require("../../common/utils"); function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; } const { log } = (0, _snooplogg.default)('engage: delete'); const action = async ({ argv, console }) => { const { baseUrl, account, file, wait, args, region, cache, yes, forceDelete } = argv; let isCmdError = true; // let's be pessimistic. const typedResource = args[0]; const typedName = args[1]; let bulkResults = { success: [], error: [] }; const render = new _Renderer.default(console); const client = new _ApiServerClient.ApiServerClient({ baseUrl, account, region, useCache: cache }); const defsManager = new _DefinitionsManager.DefinitionsManager(client); if (file && args.length) { render.error('Error: Invalid command arguments, please provide a file path or resource type and name.'); console.log(`\nUSAGE: To delete resources by filenames:\t"axway engage delete -f/--file <path> To delete a single resource:\t\t"axway engage delete <Resource> <Name>"`); process.exit(1); } try { log(`load and verify specs`); await defsManager.init(); const scope = (0, _utils.parseScopeParam)(argv.scope); if (!file && !args.length) { // user typed just "axway engage delete" render.error('Error: You must specify the type and name of the resource to delete or a file path.'); console.log(`\nUSAGE: To delete resources by filename: ${_chalk.default.cyan(`axway engage delete -f/--file <path>`)}\n To delete a single non-scoped resource: ${_chalk.default.cyan(`axway engage delete <Resource> <Name>`)}\n To delete a scoped resource in all scopes with a specific name without confirmation dialog: ${_chalk.default.cyan(`axway engage delete <Resource> <Name> -s/--scope <Scope Name> --yes`)}\n To delete a scoped resource in a specific scope: ${_chalk.default.cyan(`axway engage delete <Resource> <Name> -s/--scope <Scope Kind>/<Scope Name>`)}\n The server supports the following resources: ${defsManager.getDefsTableForHelpMsg()}`); process.exit(1); } if (args.length) { // SINGLE RESOURCE MODE log(`executing api calls in single delete mode`); const defs = defsManager.findDefsByWord(typedResource); if (!defs) throw Error(`the server doesn't have a resource type "${typedResource}"`); if (!typedName) throw Error('resource name is required.'); if (defs.every(defs => !!defs.scope) && !scope) throw Error(`scope name param (-s/--scope) is required for the scoped "${defs[0].resource.spec.kind}" resource.`); (0, _utils.verifyScopeParam)(defsManager.getAllKindsList(), defs, scope); // find needed defs by specified resource type + scope name + scope kind (if provided) const matchingDefs = defs.filter(defs => { var _defs$scope; return scope && (scope.kind && scope.kind === ((_defs$scope = defs.scope) === null || _defs$scope === void 0 ? void 0 : _defs$scope.spec.kind) || !scope.kind && !!defs.scope) || !scope && !defs.scope; }); // this should never happen, the filtering logic is probably invalid if true if (!matchingDefs.length) throw Error(`can't find matching resource definitions.`); // Ask user if it's okay to delete unless the "--yes" option is set. // Note: Only prompt if it ends up deleting multiple associated resources. if (!yes) { let result = _types.YesNo.Yes; if (!scope) { result = await (0, _basicPrompts.askList)({ msg: 'Deleting this will delete all resources under its scope. Are you sure you want to do this?', choices: _types.YesNoChoices, default: _types.YesNo.No }); } else if (matchingDefs.length > 1) { result = await (0, _basicPrompts.askList)({ msg: 'The resource may exist in many scopes, and multiple entities might be deleted. Do you want to continue?', choices: _types.YesNoChoices, default: _types.YesNo.No }); } if (result === _types.YesNo.No) { process.exit(1); } } // Ask user if it's okay to delete when "--forceDelete" option is set. if (!yes && forceDelete) { let result = _types.YesNo.Yes; result = await (0, _basicPrompts.askList)({ msg: 'Are you sure you want to force delete this resource?', choices: _types.YesNoChoices, default: _types.YesNo.No }); if (result === _types.YesNo.No) { process.exit(1); } } render.startSpin(`Deleting resources${wait ? ' and waiting for them to be deleted' : ''}`); const results = await Promise.all(matchingDefs.map(async defs => client.deleteResourceByName({ resourceDef: defs.resource, resourceName: typedName, scopeDef: defs.scope, scopeName: scope === null || scope === void 0 ? void 0 : scope.name, wait, forceDelete }))); // considering the command successful if at least 1 response found isCmdError = !results.filter(res => res.data !== null).length; results.forEach(res => { var _res$error, _res$error2; // rendering errors only if the command is unsuccessful if (isCmdError && (_res$error = res.error) !== null && _res$error !== void 0 && _res$error.length) render.anyError(res.error[0]);else if (!((_res$error2 = res.error) !== null && _res$error2 !== void 0 && _res$error2.length)) render.success(`${render.resourceAndScopeKinds(res.data)} has successfully been deleted.`); // mind the non-null assertion }); } else if (file) { // BULK MODE render.startSpin(`Deleting resources${wait ? ' and waiting for them to be deleted' : ''}`); log(`executing api calls in bulk delete mode`); log(`verifying file: ${file}`); (0, _utils.verifyFile)(file); const { docs } = await (0, _utils.loadAndVerifySpecs)(file, defsManager.getAllKindsList()); bulkResults = await client.bulkDelete(docs, defsManager.getSortedKindsMap(), wait, forceDelete); render.bulkResult(bulkResults, 'has successfully been deleted.'); isCmdError = !!bulkResults.error.length; } } catch (e) { log('command error', e); // if some calls finished, rendering the result if (bulkResults.success.length || bulkResults.error.length) render.bulkResult(bulkResults, 'has successfully been deleted.'); render.anyError(e); } finally { log(`command finished, success = ${!isCmdError}`); render.stopSpin(); isCmdError && process.exit(1); } }; const deleteCmd = exports.deleteCmd = { action, desc: 'Delete resources', args: [{ name: 'args', desc: 'Command arguments, run "axway engage delete" to see the examples', multiple: true, required: false, type: 'string' }], options: { ..._types.commonCmdArgsDescription, '-f, --file [path]': { desc: `Filename to use to delete the resource.`, type: 'string' }, '-s, --scope [name] or [kind/name]': { desc: `Scope name or kind/name for scoped resources.`, type: 'string' }, '-y, --yes': 'Automatically reply "yes" to any command prompts.', '--wait': 'Wait for the resources to be completely deleted.', '--forceDelete': 'Force delete a resource (Warning: Ignores finalizers on the resource and the resources scoped under it)' } };