Created
September 7, 2019 19:08
-
-
Save juancarloscruzd/8988d08e596a1cebe7c6953bb16334db to your computer and use it in GitHub Desktop.
Trigger Lambda function with SQS Queue as trigger
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
"use strict"; | |
const AWS_REGION = process.env.AWS_REGION; | |
const Promise = require("bluebird"); | |
const AWS = require("aws-sdk"); | |
const eventUtils = require("./eventUtils.js"); | |
AWS.config.update({ region: AWS_REGION }); | |
AWS.config.setPromisesDependency(Promise); | |
class Dispatcher { | |
constructor() { | |
this.PUBLISHED_QUEUE_URL = process.env.PUBLISHED_QUEUE_URL; | |
this.AWS_ACCOUNTID = process.env.AWS_ACCOUNTID; | |
this.sns = undefined; | |
this.sqs = undefined; | |
} | |
init() { | |
this.sns = new AWS.SNS(); | |
this.sqs = new AWS.SQS(); | |
} | |
//-------------------------------------------------------- | |
// --- Dispatches the event to the topic corresponding to it's type | |
//-------------------------------------------------------- | |
dispatchEvent(event, topic) { | |
var params = { | |
TopicArn: | |
"arn:aws:sns:" + AWS_REGION + ":" + this.AWS_ACCOUNTID + ":" + topic, | |
Subject: event.eventType, | |
Message: eventUtils.stringify(event) | |
}; | |
return this.sns.publish(params).promise(); | |
} | |
//-------------------------------------------------------- | |
// --- Dispatches all the events | |
//-------------------------------------------------------- | |
dispatchAll(events) { | |
return Promise.all( | |
events.map(() => this.dispatchEvent(event, event.eventType)) | |
); | |
} | |
} | |
exports.Dispatcher = Dispatcher; | |
//---------------------------- | |
// --- Handles the incoming event from SQS | |
//---------------------------- | |
exports.handler = function(sqsEvent, context, callback) { | |
let dispatcher = new Dispatcher(); | |
dispatcher.init(); | |
const events = sqsEvent.Records.filter(event => | |
eventUtils.getOriginal(JSON.parse(event.body)) | |
); | |
dispatcher | |
.dispatchAll(events) | |
.then(data => { | |
callback(undefined, data); | |
}) | |
.catch(callback); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment