Saturday, March 6, 2021

How to use Javascript AWS SNS SDK

// Use AWS-SDK

import * as AWS from 'aws-sdk';


// Known constants

const fcmToken = 'SAMPLE_FCM_TOKEN';

const applicationArn = 'FCM_APPLICATION_ARN';

const topicArn = 'SNS_TOPIC_ARN';



// Initialize SNS

const sns = new AWS.SNS({

    apiVersion: '2010-03-31',

    accessKeyId: 'YOUR_ACCESS_KEY',

    secretAccessKey: 'YOUR_SECRET_ACCESS_KEY',

    region: 'YOUR_REGION'

});


// Function to register an application-endpoint using FCM token

async function registerDevice(deviceFcmToken: string): Promise<string> {

    console.log('Registering device endpoint');

    const endpointArn = await sns.createPlatformEndpoint({

        PlatformApplicationArn: applicationArn,

        Token: deviceFcmToken

    })

    .promise()

    .then((data) => {

        return data.EndpointArn;

    })

    .catch((error) => {

        return null;

    });

    return endpointArn;

}


// Function to subscribe to an SNS topic using an endpoint

async function subscribeToSnsTopic(endpointArn: string): Promise<string> {

    console.log('Subscribing device endpoint to topic');

    const subscriptionArn = await sns.subscribe({

        TopicArn: topicArn,

        Endpoint: endpointArn,

        Protocol: 'application'

    })

    .promise()

    .then((data) => {

        return data.SubscriptionArn;

    })

    .catch((error) => {

        return null;

    });

    return subscriptionArn;

}


// Send SNS message to a topic

var params = {

    Message: 'Hello World',

    TopicArn: topicArn

};

sns.publish(params)

    .promise()

    .then((data) => {

        console.log(`Message ${params.Message} send sent to the topic ${params.TopicArn}`);

        console.log("MessageID is " + data.MessageId);

    })

    .catch((err) => {

        console.error(err, err.stack);

    });


references:

https://stackoverflow.com/questions/60828196/how-can-i-send-aws-sns-push-notification-using-fcm-in-nodejs 


No comments:

Post a Comment