Javi

Alexa: Proxy lambda

May 27th, 2018
345
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.13 KB | None | 0 0
  1. /** This lambda function will proxy the request to another endpoint, easily allowing local execution of the real implemenation. */
  2. const https = require('https');
  3.  
  4. exports.handler = function(event, context, callback) {
  5. console.log(`Connecting to ${process.env.HOSTNAME}${process.env.PATH}.`);
  6.  
  7. const postData = JSON.stringify({event, context});
  8. const options = {
  9. hostname: process.env.HOSTNAME,
  10. port: 443,
  11. path: process.env.PATH,
  12. method: 'POST',
  13. headers: {
  14. 'Content-Type': 'application/json',
  15. 'Content-Length': postData.length
  16. }
  17. };
  18.  
  19. const req = https.request(options, resp => {
  20. console.log('Waiting for response.');
  21. let data = '';
  22. resp.on('data', block => {
  23. console.log(`New data: ${block}.`);
  24. data+=block;
  25. });
  26. resp.on('end', () => {
  27. console.log(`Obtained data: ${data}.`);
  28. const implResponse = JSON.parse(data);
  29. callback(implResponse.err, implResponse.response);
  30. });
  31. }).on("error", err => {
  32. console.log(`Error: %s.`, JSON.stringify(err));
  33. callback(err);
  34. });
  35. req.write(postData);
  36. req.end();
  37. };
  38.  
  39. /** Here it is the other side of the coin: the proxied actual client. */
  40.  
  41. const isAWSLambda = process.env.LAMBDA_TASK_ROOT && process.env.AWS_EXECUTION_ENV;
  42.  
  43. if (!isAWSLambda) {
  44. console.log('Local execution detected. Launching server.');
  45. var express = require('express');
  46. var bodyParser = require('body-parser');
  47. var app = express();
  48. app.use(bodyParser.json());
  49. app.post('/', function(req, res) {
  50. console.log(`New request %s.`, JSON.stringify(req.body));
  51. exports.handler(req.body.event, req.body.context, (err, response) => {
  52. const skillResponse = {err, response};
  53. console.log(`Skill response: %s.`, JSON.stringify(skillResponse));
  54. res.setHeader('Content-Type', 'application/json');
  55. res.send(JSON.stringify(skillResponse));
  56. });
  57. });
  58. app.listen(80, function () {
  59. console.log('Server listening on port 80.');
  60. });
  61. }
Advertisement
Add Comment
Please, Sign In to add comment