From bc21a28741c87145154d1cf4d1cafb44fb538bda Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Markus=20M=C3=A4kel=C3=A4?= Date: Wed, 2 May 2018 08:12:03 +0300 Subject: [PATCH] Add sum helper to `api` command Calculating sums for values is useful for monitoring and scripting purposes. --- maxctrl/lib/api.js | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/maxctrl/lib/api.js b/maxctrl/lib/api.js index 835e43057..a27a30723 100644 --- a/maxctrl/lib/api.js +++ b/maxctrl/lib/api.js @@ -17,6 +17,13 @@ exports.desc = 'Raw REST API access' exports.handler = function() {} exports.builder = function(yargs) { yargs + .group(['sum'], 'API options:') + .option('sum', { + describe: 'Calculate sum of API result. Only works for arrays of numbers ' + + 'e.g. `api get --sum servers data[].attributes.statistics.connections`.', + type: 'boolean', + default: false + }) .command('get [path]', 'Get raw JSON', function(yargs) { return yargs.epilog('Perform a raw REST API call. ' + 'The path definition uses JavaScript syntax to extract values. ' + @@ -27,7 +34,11 @@ exports.builder = function(yargs) { maxctrl(argv, function(host) { return doRequest(host, argv.resource, (res) => { if (argv.path) { - res = _.getPath(res, argv.path, '') + res = _.getPath(res, argv.path) + } + + if (argv.sum && Array.isArray(res) && typeof(res[0]) == 'number') { + res = res.reduce((sum, value) => value ? sum + value : sum) } return JSON.stringify(res)