Created
December 16, 2015 20:35
-
-
Save horsey/08dcb29a0e1f172eb82d to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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