How to publish FROM an AWS lambda to a cloud watch metric in Node.js
<p>Inside a lambda I use to periodically check in on a service I check the value of the result from the server and I want that value published to AWS cloudwatch as a metric to form a linechart. </p>

<p>I can't for the life of me figure our how this is done. 2 hours combing around the AWS docs leads nowhere.Is this even possible?</p>

<p>To be clear this isn't a metric ABOUT a lambda, it's <strong>a metric published FROM the lamdba.</strong></p>

<p>Code:</p>

<pre><code>'use strict';

const https = require('http');


exports.handler = (event, context, callback) =&gt; {
  const now = new Date()
  const yesterday = new Date(now.toISOString())
  yesterday.setTime(now.getTime()  - (1000 * 60 * 60 * 24)); // 1 day ago)

  const params = [
    ['limit',0],
    ['pageStart',0],
    ['startsOnOrAfter',encodeURIComponent(yesterday.toISOString())],
    ['startsOnOrBefore',encodeURIComponent(now.toISOString())]
  ].map(kv =&gt; `${kv[0]}=${kv[1]}&amp;`).reduce((s1,s2) =&gt; s1.concat(s2))

  var uri = `http://service/query?${params}`
  const req = https.request(uri, (res) =&gt; {
    let body = '';
    res.setEncoding('utf8');
    res.on('data', (chunk) =&gt; body += chunk);
    res.on('end', () =&gt; {
      if (!res.headers[ 'content-type' ].match('application/.*?json')) {
        return callback(`unknown content type ${res.headers[ 'content-type' ]}`,body)
      }
      body = JSON.parse(body);
      if(body.total &amp;&amp; body.total &gt; 0) {
        callback(null, body.total); // body.total to form a line chart
      }
      else {
        callback({
          message: 'No plans found for time period',
          uri: uri
        })
      }
    });
  });
  req.on('error', callback);
  req.end();
};
</code></pre>