How to use the SNS function from aws-sdk

Find comprehensive JavaScript aws-sdk.SNS code examples handpicked from public code repositorys.

aws-sdk.SNS is a module that provides methods for interacting with Amazon Simple Notification Service (SNS) in order to send and receive messages between distributed software components.

278
279
280
281
282
283
284
285
286
287

AWS.config.update({
  endpoint: `http://localhost:${port}`
})
agent.startTransaction('myTransaction')
const publishTextPromise = new AWS.SNS({ apiVersion: '2010-03-31' })
  .publish(params).promise()
t.ok(agent.currentSpan === null, 'no currentSpan in sync code after sns.publish(...).promise()')

// Handle promise's fulfilled/rejected states
fork icon211
star icon536
watch icon296

+ 113 other calls in file

16
17
18
19
20
21
22
23
24

/* Lambda Function to use AWS IoT button to send check-in/check-out notifications using an SNS Topic. */

'use strict';
const AWS = require('aws-sdk');
const SNS = new AWS.SNS({ apiVersion: '2010-03-31' });

// !!CHANGE THIS (1 of 3)!! Enter the ARN of your SNS Topic
const TOPIC_ARN = 'arn:aws:sns:us-west-2:XXXXXXXXXXXX:IoT-Button-CheckIn';
fork icon5
star icon9
watch icon51

How does aws-sdk.SNS work?

aws-sdk.SNS works by providing a set of methods that allow you to interact with the Amazon Simple Notification Service (SNS) API.

The module allows you to create a new SNS client by calling new AWS.SNS().

You can then use the client to call methods such as createTopic, subscribe, and publish to create topics, subscribe to topics, and publish messages to topics.

The SNS service can be used to send notifications or messages to a large number of recipients or subscribers, and can be integrated with other AWS services to trigger actions based on these notifications.

By using aws-sdk.SNS, you can easily interact with the Amazon SNS service in order to send and receive messages between distributed software components.

10
11
12
13
14
15
16
17
18
19
const lambda = new aws.Lambda({ region: awsRegion }),
        logs = new aws.CloudWatchLogs({ region: awsRegion }),
        apiGatewayPromise = retriableWrap(new aws.APIGateway({ region: awsRegion })),
        s3 = new aws.S3(),
        iot = new aws.Iot({ region: awsRegion }),
        sns = new aws.SNS({ region: awsRegion }),
        events = new aws.CloudWatchEvents({ region: awsRegion }),
        cognitoIdentityServiceProvider = new aws.CognitoIdentityServiceProvider({ region: awsRegion }),
        destroyRule = function (ruleName) {
                return events.listTargetsByRule({ Rule: ruleName }).promise()
fork icon290
star icon0
watch icon3

148
149
150
151
152
153
154
155
156
157

Example 1:

```js
const AWS      = require('aws-sdk');
const sns      = AWS.SNS();
const dynamoDb = AWS.DynamoDB();

exports.handler = function(event, context) {
  // do something with the services e.g. sns.publish
fork icon108
star icon0
watch icon12

+ 7 other calls in file

Ai Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
const AWS = require("aws-sdk");

// Create a new SNS client
const sns = new AWS.SNS();

// Publish a message to an SNS topic
sns.publish(
  {
    TopicArn: "arn:aws:sns:us-west-2:123456789012:example-topic",
    Message: "Hello, world!",
  },
  (err, data) => {
    if (err) {
      console.log(err);
    } else {
      console.log("Message sent:", data.MessageId);
    }
  }
);

In this example, we first create a new aws-sdk.SNS client by calling new AWS.SNS(). We then use the publish method to send a message to an SNS topic with an ARN of 'arn:aws:sns:us-west-2:123456789012:example-topic'. The message itself is simply the string 'Hello, world!'. We provide a callback function that logs an error message if the publish method returns an error, or the message ID if the message was sent successfully. The resulting output demonstrates how aws-sdk.SNS can be used to send a message to an SNS topic.

3
4
5
6
7
8
9
10
11
12
    sendToSns,
    getPayloadFromSnsEvent
};

const AWS = require('aws-sdk');
const sns = new AWS.SNS();

function sendToSns (data) {
    const params = {
        Message: JSON.stringify(data),
fork icon85
star icon662
watch icon16

+ 3 other calls in file

52
53
54
55
56
57
58
59
60
61
const zlib = require('zlib');
const aws = require('aws-sdk');
const { promisify } = require('util');

const gunzip = promisify(zlib.gunzip);
const sns = new aws.SNS();

exports.handler = async (event) => {
  const payload = Buffer.from(event.awslogs.data, 'base64');
  const decompressedData = await gunzip(payload);
fork icon105
star icon228
watch icon25

513
514
515
516
517
518
519
520
521
522
523
    }
    assert.fail(`"process_job_event_status, unexpected status ${status}"`);
}


var publish_to_log_topic = function(message) {
    var sns = new AWS.SNS();
    var request_topic = sns.createTopic({Name: log_topic_name,}, function(err, data) {
            if (err) {
              console.log("ERROR: Failed to SNS CREATE TOPIC");
            }
fork icon46
star icon36
watch icon17

+ 9 other calls in file

9
10
11
12
13
14
15
16
17
18
const {LifeCycleEvents} = require('./constants');
const express = require('express');
const app = express();
const getString = bent('string');
const AWS = require('aws-sdk');
const sns = new AWS.SNS({apiVersion: '2010-03-31'});
const autoscaling = new AWS.AutoScaling({apiVersion: '2011-01-01'});
const {Parser} = require('xml2js');
const parser = new Parser();
const {validatePayload} = require('verify-aws-sns-signature');
fork icon27
star icon31
watch icon0

13
14
15
16
17
18
19
20
21
22
		accessKeyId: process.env.AWS_ACCESS_KEY || "",
		secretAccessKey: process.env.AWS_SECRET_KEY || ""
	}
})
const SES = new aws.SES()		
const SNS = new aws.SNS()
 
// [DEPRECATED] Use the `/push` endpoint with a `slack:{hook}` device token.
// Only for Slack support. Format: "XXXXXXXXX/XXXXXXXXXXX/XXXXXXXXXXXXXXXXXXXXXXXX".
const SLACK_HOOK = process.env.SLACK_HOOK || ""
fork icon1
star icon2
watch icon3

1
2
3
4
5
6
7
8
9
10
11
12
13


const AWS = require('aws-sdk')
const Joi = require('joi')


const S3 = new AWS.S3()
const SNS = new AWS.SNS()


const schema = Joi.object().keys({
    TodoId: Joi.string().required(),
    Task: Joi.string().required(),
fork icon0
star icon1
watch icon1

71
72
73
74
75
76
77
78
79
80

/**
 * Publish a SNS message so that a log entry containing the integTestId is sent to cloudwatch
 */
const publishMessage = (integTestId) => {
  const client = new AWS.SNS();
  return client
    .publish({
      Subject: `IntegTest: ${integTestId}`,
      Message: `integ-test-${integTestId}`,
fork icon0
star icon0
watch icon1

+ 3 other calls in file

15
16
17
18
19
20
21
22
23
24
var params = {
  Message: 'Para realizar el cambio debe confirmar su identidad con el código '+otp,
  PhoneNumber: '57'+phone
};
console.log("ENVIANDO A "+JSON.stringify(params));
var sns = new AWS.SNS({apiVersion: '2010-03-31'});
return sns.publish(params, function(err, data) {
    if (err) {
      console.log("Error", err);
    } else {
fork icon0
star icon0
watch icon1

+ 25 other calls in file

62
63
64
65
66
67
68
69
70
71
}
// const params = {
//   Message: messages.generateotp(otp),
//   PhoneNumber: phone,
// };
// const publishTextPromise = new AWS.SNS();

// publishTextPromise.publish(params, (err, data) => {
//   if (err) {
//     throw new Error({ Details });
fork icon0
star icon0
watch icon1

+ 9 other calls in file

176
177
178
179
180
181
182
183
184
185
186
187
});


//subscription feature
router.post("/subscribe", async (req, res) => {
  let secrets = await getSecret();
  const sns = new AWS.SNS({ region: "us-east-1" });


  const params = {
    Protocol: "email",
    TopicArn: secrets.sns_arn,
fork icon0
star icon0
watch icon0

4
5
6
7
8
9
10
11
12
13
// args.region
exports.main = function () {
};

exports.createSNS = function (args) {
        return new AWS.SNS({
                accessKeyId: args.aws_access_key_id,
                secretAccessKey: args.aws_secret_access_key,
                apiVersion: '2010-03-31',
                region: args.region
fork icon0
star icon0
watch icon3

+ 13 other calls in file