Find us on facebook

Showing posts with label AWS Lambda. Show all posts
Showing posts with label AWS Lambda. Show all posts

Oct 29, 2016

Send pushnote to device with AWS Lambda Nodejs

var params = {'PlatformApplicationArn':platformApplicationArn,'Token': token};

sns.createPlatformEndpoint(params,function(err,EndPointResult)
    {
        if(EndPointResult != null){
          var clientArn = EndPointResult["EndpointArn"];
          sns.publish(
            {
              TargetArn: clientArn,
              Message: JSON.stringify(clientMessage),
              Subject: JSON.stringify(subject),
              MessageStructure: 'json'
            },
            function(err,data){
              if (err) {
                  console.log("Error sending a message "+err+JSON.stringify(params.Token));
                  if(err == "EndpointDisabled: Endpoint is disabled"){
                    sns.deleteEndpoint({'EndpointArn': clientArn}, function(err, data) {
                      if (err) console.log("Error removing Endpoint Arn: "+err);
                    });
                    message.deleteMessage(function(err, data) {
                      if(err){
                        console.log("Error deleting message: "+err);
                      }
                      message.next();
                    });
                  }
                  message.next();
              } else {
                  var messagedate = new Date();
                  console.log("Sent message: "+data.MessageId+messagedate+JSON.stringify(params));
                  sns.deleteEndpoint({'EndpointArn': clientArn}, function(err, data) {
                    if (err) console.log("Error removing Endpoint Arn: "+err);
                  });
                  message.deleteMessage(function(err, data) {
                    if(err){
                      console.log("Error deleting message: "+err);
                    }
                    message.next();
                  });
              }
            }
          );
        }
        if(EndPointResult == null){
          message.next();
        }
       
    });

Send message to a queue with AWS Lambda Nodejs

Following parameters need to be passed.
var params = {
            MessageBody: JSON.stringify({"platformApplicationArn":arn,
              'token':token_id,
              'message': messageBody,
              'subject':subject,
             }),
            QueueUrl: "https://sqs.ap-region-x.amazonaws.com/xxxxxxxxxxxx/2ndqueue"
      };

Send message to the queue.
sqs.sendMessage(params, function(err, data) {
    if (err){
      console.log(err, err.stack);
     
    }
    else {
      console.log(data);
    }
});

Connection pool and query within Lambda nodejs runtime

var pool = openConnectionToDB(host,username,password,database);

pool.getConnection(function(err,connection){
console.log('connected as id ' + connection.threadId);
        //Query
connection.query("SELECT * FROM ?? WHERE ?? = ? AND deleted_at IS NULL",['table_name','id',subject],function(err,rows){
           if(!err) {
             if(typeof rows[0] == 'undefined'){
               connection.release();
               connection.destroy();
             }
           }
 });
});

Using SqsQueueParallel to receive messages parallaly from a queue

var queue = new SqsQueueParallel({
      name: "queue1",
      region:process.env.REGION,
      accessKeyId:process.env.ACCESS_KEY_ID,
      secretAccessKey:process.env.SECRET_ACCESS_KEY,
      maxNumberOfMessages: 10,
      concurrency: 10
});

queue.on('message', function (message)
{
//more code
});

Lambda Function Basic

Create serverless function.
serverless function create functions/Function1/func1 (This command should be given within the project folder)

Within Function1 folder it creates
func1 folder and package.json file

Within func1 folder it creates following files.
event.json
handler.js
s-function.json

In handler.js file, we can include all the functions.

First we need to get required packages as below.

var aws = require('aws-sdk');
var SqsQueueParallel = require('sqs-queue-parallel');
var sqs = new aws.SQS({"accessKeyId":process.env.ACCESS_KEY_ID, "secretAccessKey": process.env.SECRET_ACCESS_KEY, "region": process.env.REGION});

Within handler function we can include the logic we want.

module.exports.handler = function(event, context, cb) {
};

s-function.json structure will be like
{
  "name": "func1",
  "runtime": "nodejs4.3",
  "description": "Serverless Lambda function for project: XXXXX",
  "customName": "func1",
  "customRole": "arn:aws:iam::xxxxxxxxxxxx:role/role",
  "handler": "func1/handler.handler",
  "timeout": 300,
  "memorySize": 128,
  "authorizer": {},
  "custom": {
    "excludePatterns": []
  },
  "endpoints": [],
  "events": [
    {
      "name": "V1Schedule",
      "type": "schedule",
      "config": {
        "schedule": "rate(5 minutes)",
        "enabled": true
      }
    }
  ],
  "environment": {
    "SERVERLESS_PROJECT": "${project}",
    "SERVERLESS_STAGE": "${stage}",
    "SERVERLESS_REGION": "${region}",
    "ACCESS_KEY_ID": "AWSKEYHERE",
    "SECRET_ACCESS_KEY": "AWSSECRETHERE",
    "REGION": "ap-southeast-1",
    "LIMIT": "300"
  },
  "vpc": {
    "securityGroupIds": [],
    "subnetIds": []
  }
}

package.json structure will be like,
{
  "name": "LambdaFunction",
  "version": "0.0.1",
  "description": "A Serverless Project and its Serverless Plugin dependencies.",
  "author": "ishara",
  "license": "MIT",
  "private": false,
  "repository": {
    "type": "git",
    "url": "git://github.com/"
  },
  "dependencies": {
    "async-foreach": "^0.1.3",
    "mysql": "^2.11.1",
    "object-sizeof": "^1.0.10",
    "sqs-queue-parallel": "^0.1.6"
  }
}

Pushnotification proceesor with AWS Lambda

Push Notification Processor is a microservice developed using AWS Lambda Node.js 4.3 runtime. To deploy the Lambda functions to AWS, the serverless framework is used.

Process:
To send bulk pushnotes, we use two SQS queues.
Platform -> 1st queue -> Execute 1st Lambda function -> 2nd queue -> Execute 2nd Lambda function to send pushnote to device

To execute lambda functions, we need a Role that has permission AmazonSQSFullAccess,AmazonSNSFullAccess

We can assign permissions to a role through AWS IAM (Identity Access Management).

In handler.js file, we can include all the functions.