Amazon SNS Example with NodeJS Express and NestJS

Problem

There are few simple Examples how to set up Amazon SNS with NodeJS. It can be taking a lot of time (and money) to dig through documentation and trial and error until you have a working base set up.

Solution

Requirements

Installed NodeJS

Installed LocalStack (see here: https://thestrugglingdeveloper.com/2021/02/18/install-localstack/)

I will show you an example set up in Express and NestJS.

Implementation with Express

To start install express as you are used to.

Then run npm install --save aws-sdk body-parser

This will provide you with the packages you require to go ahead.

const express = require('express');
const bodyParser = require('body-parser');

const app = express();

const AWS = require('aws-sdk');
const credentials = new AWS.Credentials({'accessKeyId': 'test', 'secretAccessKey': 'test'})

const sns = new AWS.SNS({credentials: credentials, region: 'us-east-1', endpoint: 'http://localhost:4566'});

const port = 3000;
const ARN = 'arn:aws:sns:us-east-1:000000000000:test1'
// app.use(util.overrideContentType());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(bodyParser.raw());
app.use(bodyParser.text({ type: 'text/plain' }));

app.post('/test1', (req, res) => {
    try {
        return res.json({status: "ok", sns: sns})
    } catch (e) {
        console.error(e)
    }
});
app.get('/status', (req, res) => res.json({status: "ok", sns: sns}));

app.post('/subscribe', (req, res) => {
    let params = {
        Protocol: 'http',
        TopicArn: ARN,
        Endpoint: 'http://docker.for.mac.localhost:3000/test1'
    };

    sns.subscribe(params, (err, data) => {
        if (err) {
            console.log(err);
        } else {
            console.log(data);
            res.send(data);
        }
    });
});

app.post('/confirmsub', (req, res) => {
    const params = {
        TopicArn: ARN,
    }
    sns.confirmSubscription(params, (err, data) => {

    })
})
app.post('/unsubscribe', (req, res) => {
    let params = {
        SubscriptionArn: 'ARN:9288ff70-b896-46ce-bcce-e2f2ff35c71d',
    };

    sns.unsubscribe(params, (err, data) => {
        if (err) {
            console.log(err);
        } else {
            console.log(data);
            res.send(data);
        }
    });
});

app.post('/publish', (req, res) => {
    var params = {
        Message: 'STRING_VALUE', /* required */
        TopicArn: ARN
    };
    sns.publish(params, function(err, data) {
        if (err) {
            console.log('Publish error')
            console.log(err, err.stack);
        } // an error occurred
        else     console.log(data);           // successful response
    });

});

app.listen(port, () => console.log(`SNS App listening on port ${port}!`));

Line 6 (const AWS = require(‘aws-sdk’);) gives us access to the SDK

Line 7 (const credentials = new AWS.Credentials({'accessKeyId': 'test', 'secretAccessKey': 'test'}) creates the credentials

Line 8 (const sns = new AWS.SNS({credentials: credentials, region: 'us-east-1', endpoint: 'http://localhost:4566'});) finally creates the SNS Connection.

LocalStack exposes all services under http://localhost:4566

Line 19-25 define the method that receives the sns call.

Line 26 is simply for debugging purposes

Line 28-43 represent the route which you can call to set up a subscription

Implementation with NestJS

Sources:

https://webcache.googleusercontent.com/search?q=cache:9h_WddCu2a4J:https://forums.aws.amazon.com/thread.jspa%3FthreadID%3D113346+&cd=4&hl=en&ct=clnk&gl=au

https://docs.aws.amazon.com/cli/latest/reference/sns/publish.html

https://docs.aws.amazon.com/sns/latest/dg/sns-message-and-json-formats.html#http-subscription-confirmation-json

https://docs.aws.amazon.com/cli/latest/userguide/cli-services-sns.html

https://docs.aws.amazon.com/cli/latest/reference/sns/publish.html

https://stackabuse.com/get-http-post-body-in-express-js/

https://github.com/localstack/localstack/issues/350

https://stackoverflow.com/questions/18484775/how-do-you-access-an-amazon-sns-post-body-with-express-node-js

Leave a Reply