Created
December 11, 2015 17:38
-
-
Save soulcutter/6d7a67f79fdd3ef62465 to your computer and use it in GitHub Desktop.
Publishing to an SNS topic in AWS lambda (as a promise)
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 _ = require('lodash'); | |
var Q = require('q'); | |
var AWS = require('aws-sdk-q'); | |
function SnsPublisher(topic, options) { | |
var topicOptions = { | |
params: { | |
TopicArn: topic | |
} | |
}; | |
var clientOptions = _.defaultsDeep( | |
topicOptions, | |
options, | |
this.clientDefaults | |
); | |
this.sns = new AWS.SNS(clientOptions); | |
} | |
SnsPublisher.prototype = { | |
clientDefaults: { | |
params: { | |
region: 'us-east-1' | |
}, | |
maxRetries: 1 | |
}, | |
publish: function(subject, message) { | |
if (message.length == 0) return Q(undefined); // no-op promise | |
if (!_.isString(message)) { | |
message = JSON.stringify(_.toPlainObject(message), null, 2); | |
} | |
var params = { | |
Subject: subject, | |
Message: message | |
}; | |
return this.sns.publish(params).q().fail(this.publishFailed); | |
}, | |
publishFailed: function(error) { | |
if (error.stack) { return console.log(error.stack); } | |
if (error.message) { return console.log(error.message); } | |
return console.log(error); | |
} | |
}; | |
module.exports = SnsPublisher; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment