From c86e09a63c2c4e6ea156e9d38ee8cbb00d2fa5ff Mon Sep 17 00:00:00 2001 From: Vlad Golubev Date: Fri, 6 Jan 2017 20:33:33 +0200 Subject: [PATCH] Refactor calculating metrics counts --- lib/plugins/aws/metrics/awsMetrics.js | 42 +++++++++------------------ 1 file changed, 13 insertions(+), 29 deletions(-) diff --git a/lib/plugins/aws/metrics/awsMetrics.js b/lib/plugins/aws/metrics/awsMetrics.js index 070e7158c..7b9f3fa85 100644 --- a/lib/plugins/aws/metrics/awsMetrics.js +++ b/lib/plugins/aws/metrics/awsMetrics.js @@ -6,13 +6,6 @@ const _ = require('lodash'); const moment = require('moment'); const validate = require('../lib/validate'); -// helper functions -const getRoundedAvgDuration = (duration, functionsCount) => -(Math.round(duration * 100) / 100) / functionsCount; - -const reduceDatapoints = (datapoints, statistic) => datapoints - .reduce((previous, datapoint) => previous + datapoint[statistic], 0); - class AwsMetrics { constructor(serverless, options) { this.serverless = serverless; @@ -190,33 +183,24 @@ class AwsMetrics { message += `${formattedStartTime} - ${formattedEndTime}\n\n`; if (metrics && metrics.length > 0) { - let invocations = 0; - let throttles = 0; - let errors = 0; - let duration = 0; + const getDatapointsByLabel = (Label) => { + return _.chain(metrics).flatten().filter({ Label }).map('Datapoints').flatten().value(); + }; + + const invocationsCount = _.sumBy(getDatapointsByLabel('Invocations'), 'Sum'); + const throttlesCount = _.sumBy(getDatapointsByLabel('Throttles'), 'Sum'); + const errorsCount = _.sumBy(getDatapointsByLabel('Errors'), 'Sum'); + const durationAverage = _.meanBy(getDatapointsByLabel('Duration'), 'Average'); - _.forEach(metrics, (metric) => { - _.forEach(metric, (funcMetric) => { - if (funcMetric.Label === 'Invocations') { - invocations += reduceDatapoints(funcMetric.Datapoints, 'Sum'); - } else if (funcMetric.Label === 'Throttles') { - throttles += reduceDatapoints(funcMetric.Datapoints, 'Sum'); - } else if (funcMetric.Label === 'Errors') { - errors += reduceDatapoints(funcMetric.Datapoints, 'Sum'); - } else { - duration += reduceDatapoints(funcMetric.Datapoints, 'Average'); - } - }); - }); - const formattedDuration = `${getRoundedAvgDuration(duration, metrics.length)}ms`; // display the data - message += `${chalk.yellow('Invocations:', invocations, '\n')}`; - message += `${chalk.yellow('Throttles:', throttles, '\n')}`; - message += `${chalk.yellow('Errors:', errors, '\n')}`; - message += `${chalk.yellow('Duration (avg.):', formattedDuration)}`; + message += `${chalk.yellow('Invocations:', invocationsCount, '\n')}`; + message += `${chalk.yellow('Throttles:', throttlesCount, '\n')}`; + message += `${chalk.yellow('Errors:', errorsCount, '\n')}`; + message += `${chalk.yellow('Duration (avg.):', `${durationAverage}ms`)}`; } else { message += `${chalk.yellow('There are no metrics to show for these options')}`; } + this.serverless.cli.consoleLog(message); return BbPromise.resolve(message); }