Skip to content

Instantly share code, notes, and snippets.

@mattbajorek
Created October 9, 2021 01:53
Show Gist options
  • Save mattbajorek/b4fd56dae687ef51902e09baae4b8263 to your computer and use it in GitHub Desktop.
Save mattbajorek/b4fd56dae687ef51902e09baae4b8263 to your computer and use it in GitHub Desktop.
AWS Lambda code receiving API Gateway information for SNS notifications
const AWS = require('aws-sdk');
const sns = new AWS.SNS({ apiVersion: '2010-03-31' });
exports.handler = async (event, context) => {
let body;
let statusCode = '200';
const { origin } = event.headers;
const acceptedOrigins = ['http://localhost:8080', 'https://mywebsite.com']; // PLACE PROPER WEBSITE ORIGIN
const headers = {
'Access-Control-Allow-Headers': 'Content-Type',
'Access-Control-Allow-Origin': acceptedOrigins.includes(origin) ? origin : acceptedOrigins[1],
'Access-Control-Allow-Methods': 'POST,OPTIONS'
};
try {
const { method } = event.requestContext.http;
switch (method) {
case 'OPTIONS':
break;
case 'POST':
statusCode = '201';
const { name, email, phone_number } = JSON.parse(event.body);
await sns.publish({
Message: `Name: ${name}\nEmail: ${email}\nPhone Number: ${phone_number}`,
TopicArn: 'arn:aws:sns:' // PLACE PROPER TOPIC ARN HERE
}).promise();
break;
default:
throw new Error(`Unsupported method "${method}"`);
}
} catch (err) {
statusCode = '400';
body = err.message;
} finally {
body = JSON.stringify(body);
}
return {
statusCode,
body,
headers,
};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment