Sarcel Sarcel - 22 days ago 10
Node.js Question

AWS Lambda putting item from MQTT request

I try to put MQTT request content into DynamoDB with Lambda function with this script :

var AWS = require("aws-sdk");
var dynamodb = new AWS.DynamoDB();

exports.handler = function index(e,ctx,callback){

//var msg = JSON.stringify(ctx);
var msg = e.Name;
var params = {
TableName:"myTable",
Item:{
Val: {S: msg},
ValId: { S:"Id"}
}
};


dynamodb.putItem(params,callback);
callback(null,"Putting item Marcel !!");

}


I have create/set thing/rule/policy and this script work but, i have undefined value, i try to get MQTT content for store it into DB.
For test this i post new topic with SNS, i didn't use the correct format i have post some message like this (raw):


{"Val":"Value"}
Val:"Value"
"Val":Value

Answer

I find a way to solve this with :

var AWS = require("aws-sdk");
var dynamodb = new AWS.DynamoDB();

exports.handler = function index(e,ctx,callback){
// new block
const record = e.Records[0].Sns.Message;  
var msgJSON = JSON.parse(record);         
var msg = msgJSON.key1;                   
var msg2 = msgJSON.key2;                      
var string_to_send = JSON.stringify(msg)+"-"+JSON.stringify(msg2);
//
var clean_string = string_to_send.split('"').join('');

var params = {
        TableName:"myTable",
        Item:{
            Val: {S: clean_string},
            ValId: {S: "Id"}
        }
    };


    dynamodb.putItem(params,callback);
    callback(null,"Putting item Marcel !!");

}

For test this you need use SNS to publish in topic like this :

{"key1": {"TheValue1"},"key2": {"TheValue2"}} 

or with lambda actions -> configure test event -> SNS, in the Message field put :

{\"key1\": \"Val\",\"key2\": \"ValId\"}

This work but i have useless " so i use split for delete it.