Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AWS Lambda function write to DynamoDB

I'm a beginner with Amazon Web Services and NodeJS.

I wrote a Lambda function, triggered by AWS IoT, that parse a JSON.

enter code here
use strict';

console.log('Loading function');

exports.handler = (event, context, callback) => {
   console.log('Received event:', JSON.stringify(event, null, 2));
   console.log('Id =', event.Id);
   console.log('Ut =', event.Ut);
   console.log('Temp =', event.Temp);
   console.log('Rh =', event.Rh);
   //callback(null, event.key1);  // Echo back the first key value
   //callback('Something went wrong');
};

Now I want to store the json fields into a DynamoDB table.

Any suggestion?

Thanks a lot!

like image 813
Federico Avatar asked Mar 06 '17 10:03

Federico


2 Answers

Preliminary Steps:-

  1. Create an IAM Lambda role with access to dynamodb
  2. Launch Lambda in the same region as your dynamodb region
  3. Create the DynamoDB table with correct key attributes defined

Sample code:-

The below code snippet is a sample code to give you some idea on how to put the item. Please note that it has to be slightly altered for your requirement (with table name and key attributes). It is not fully tested code.

use strict';

console.log('Loading function');
var AWS = require('aws-sdk');
var dynamodb = new AWS.DynamoDB({apiVersion: '2012-08-10'});

exports.handler = (event, context, callback) => {
    console.log(JSON.stringify(event, null, '  '));
    var tableName = "yourtablename";    
    dynamodb.putItem({
        "TableName": tableName,
        "Item" : {
            "Id": event.Id,
            "Ut": event.Ut,
            "Temp": event.Temp,
            "Rh":event.Rh
        }
    }, function(err, data) {
        if (err) {
            console.log('Error putting item into dynamodb failed: '+err);
            context.done('error');
        }
        else {
            console.log('great success: '+JSON.stringify(data, null, '  '));
            context.done('Done');
        }
    });
};

Note:-

No need to mention the data type explicitly for String and Number as long as the data type is in compliance with JavaScript String and Number. The DynamoDB will automatically interpret the data type for String and Number.

like image 143
notionquest Avatar answered Sep 27 '22 21:09

notionquest


There is also a shorter version for this with async/await:

'use strict';

const AWS = require('aws-sdk');
const dynamodb = new AWS.DynamoDB({apiVersion: '2012-08-10'});

exports.handler = async (event) => {
    const tableName = "yourtablename"; 
    try {
      await dynamodb.putItem({
          "TableName": tableName,
          "Item" : {
              "Id": event.Id,
              "Ut": event.Ut,
              "Temp": event.Temp,
              "Rh":event.Rh
          }
      }).promise();
    } catch (error) {
      throw new Error(`Error in dynamoDB: ${JSON.stringify(error)}`);
    }  
};
like image 20
PersianIronwood Avatar answered Sep 27 '22 21:09

PersianIronwood