Skip to content

Instantly share code, notes, and snippets.

@horsey
Created December 16, 2015 20:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save horsey/08dcb29a0e1f172eb82d to your computer and use it in GitHub Desktop.
Save horsey/08dcb29a0e1f172eb82d to your computer and use it in GitHub Desktop.
var aws = require('aws-sdk'),
Promise = require('bluebird'),
chalk = require('chalk'),
messageFactory = require('./factory'),
config = require('./config.json');
var sqs = new Promise.promisifyAll(new aws.SQS({
region: config.aws.region,
accessKeyId: config.aws.accessId,
secretAccessKey: config.aws.secretKey,
params: {
QueueUrl: config.aws.queueUrl
}
}));
(function pollQueueForMessages() {
console.log(chalk.yellow("Starting long-poll operation."));
sqs.receiveMessageAsync({
WaitTimeSeconds: 20,
VisibilityTimeout: 10
}).then(function handleMessageResolve(data) {
var payload,
message;
if(!data.Messages) {
throw(workflowError("EmptyQueue",
new Error("No messages to process")));
}
payload = JSON.parse(data.Messages[0].Body);
message = new messageFactory(data);
return Promise.try(function() {
return message.sendMessageAsync(data).then(function() {
return(sqs.deleteMessageAsync({
ReceiptHandle: data.Messages[0].ReceiptHandle
}));
});
}).then(function handleDeleteResolve(data) {
console.log(chalk.green("Message deleted."));
}).catch(
function handleError(error) {
switch (error.type) {
case "EmptyQueue":
console.log( chalk.cyan( "Expected Error:", error.message ) );
break;
default:
console.log( chalk.red( "Unexpected Error:", error ) );
break;
}
}
).finally(pollQueueForMessages);
})();
function workflowError(type, error) {
error.type = type;
return(error);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment