DevStarlight

sqs-poll aws example

Nov 7th, 2016
385
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. 'use strict';
  2.  
  3. const AWS = require('aws-sdk');
  4.  
  5. const SQS = new AWS.SQS({ apiVersion: '2012-11-05' });
  6. const Lambda = new AWS.Lambda({ apiVersion: '2015-03-31' });
  7.  
  8.  
  9. // TODO add your queue URL here
  10. const QUEUE_URL = '<QUEUE_URL>';
  11. const PROCESS_MESSAGE = 'process-message';
  12.  
  13.  
  14. function invokePoller(functionName, message) {
  15.     const payload = {
  16.         operation: PROCESS_MESSAGE,
  17.         message,
  18.     };
  19.     const params = {
  20.         FunctionName: functionName,
  21.         InvocationType: 'Event',
  22.         Payload: new Buffer(JSON.stringify(payload)),
  23.     };
  24.     return new Promise((resolve, reject) => {
  25.         Lambda.invoke(params, (err) => (err ? reject(err) : resolve()));
  26.     });
  27. }
  28.  
  29.  
  30. function process(message, callback) {
  31.     console.log(message);
  32.  
  33.     // TODO process message
  34.  
  35.     // delete message
  36.     const params = {
  37.         QueueUrl: QUEUE_URL,
  38.         ReceiptHandle: message.ReceiptHandle,
  39.     };
  40.     SQS.deleteMessage(params, (err) => callback(err, message));
  41. }
  42.  
  43. function poll(functionName, callback) {
  44.     const params = {
  45.         QueueUrl: QUEUE_URL,
  46.         MaxNumberOfMessages: 10,
  47.         VisibilityTimeout: 10,
  48.     };
  49.     // batch request messages
  50.     SQS.receiveMessage(params, (err, data) => {
  51.         if (err) {
  52.             return callback(err);
  53.         }
  54.         // for each message, reinvoke the function
  55.         const promises = data.Messages.map((message) => invokePoller(functionName, message));
  56.         // complete when all invocations have been made
  57.         Promise.all(promises).then(() => {
  58.             const result = `Messages received: ${data.Messages.length}`;
  59.             console.log(result);
  60.             callback(null, result);
  61.         });
  62.     });
  63. }
  64.  
  65. exports.handler = (event, context, callback) => {
  66.     try {
  67.         if (event.operation === PROCESS_MESSAGE) {
  68.             // invoked by poller
  69.             process(event.message, callback);
  70.         } else {
  71.             // invoked by schedule
  72.             poll(context.functionName, callback);
  73.         }
  74.     } catch (err) {
  75.         callback(err);
  76.     }
  77. };
Add Comment
Please, Sign In to add comment