Created
April 9, 2018 19:18
-
-
Save chrisckchang/e929a5db9e34550f7b92980908735a17 to your computer and use it in GitHub Desktop.
Express app that subscribes to SNS and displays notifications
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 express = require('express') | |
var app = express() | |
var request = require('request') | |
var bodyParser = require('body-parser') | |
// Middleware to convert SNS request message body from plain text to JSON | |
var convertToJson = function (req, res, next) { | |
if (req.headers['x-amz-sns-message-type']) { | |
req.headers['content-type'] = 'application/json;charset=UTF-8'; | |
} | |
next() | |
} | |
app.use(convertToJson) | |
// Middleware to parse the converted SNS request message body in JSON format | |
app.use(bodyParser.urlencoded({ extended: true })) | |
app.use(bodyParser.json()) | |
// Use an array to keep track of notifications. Ideally use a database to persist notifications instead. | |
var notifications = [] | |
app.get('/', function (req, res) { | |
if(notifications.length > 0) | |
{ | |
res.send(JSON.stringify(notifications)) | |
} | |
else { | |
res.send("hello world") | |
} | |
}) | |
app.post('/sns', function (req, res) { | |
// Handle subscription request | |
if(req.headers['x-amz-sns-message-type'] == "SubscriptionConfirmation") { | |
var subscribeUrl = req.body.SubscribeURL | |
request(subscribeUrl, function (err, response, body) { | |
if(err) console.log(err) | |
}) | |
} | |
// Handle notification request | |
if(req.headers['x-amz-sns-message-type'] == "Notification") { | |
notifications.push({"subject": req.body.Subject, "msg": req.body.Message}) | |
} | |
}) | |
var port = 80 | |
app.listen(port, function () { | |
console.log("SNS example app running on port " + port) | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment