'use strict';

/**
  * Lambda@Edge to log CloudFront event and context.
  * Note: this runs in Lambda@Edge which means it runs in a variety
  * of regions, the region closest to the browser making the request.
  * So be sure and check other regions if you don't see the logs in
  * CloudWatch in the region you normally use.
  * 
  * https://medium.com/@jbesw/postcards-from-lambda-the-edge-11a43f215dc1
  *
  */
exports.handler = (event, context, callback) => {

  const eventType = event.Records[0].cf.config.eventType;
  
  // Log JSON of the event and context if available to console which
  // will end up in CloudWatch
  console.log('DebugEvent ' + eventType 
    + ' -- ' + JSON.stringify(event)
    + ' -- context -- ' + JSON.stringify(context)
  );
    
  const responseEvent = eventType.indexOf('-response') > 0;
  
  // Response back to CloudFront and let the HTTP request continue  
  callback(null, 
    (responseEvent ? 
      event.Records[0].cf.response : event.Records[0].cf.request));
};