11

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!

Federico
  • 1,117
  • 6
  • 20
  • 37

2 Answers2

19

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.

notionquest
  • 37,595
  • 6
  • 111
  • 105
  • Thanks for the reply. I create a DynamoDB Table with primary Key: "Id" and Order Key: "Ut" both are strings. I create a role in IAM for Lambda with full access to DynamoDb. Unfortunately i get an error: { errorMessage": "error"} – Federico Mar 06 '17 at 12:38
  • This is the error: Error putting item into dynamodb failed: MultipleValidationErrors: There were 3 validation errors: * InvalidParameterType: Expected params.Item['Ut'].S to be a string * InvalidParameterType: Expected params.Item['Temp'].S to be a string * InvalidParameterType: Expected params.Item['Rh'].S to be a string – Federico Mar 06 '17 at 14:17
  • This seems to be a problem with the event data. Please could you check the event json whether Rh and Temp are String data types? The JSON that you use to trigger the Lambda should have these attribute value as String (i.e. with double quotes) rather than a number or date or anything else. – notionquest Mar 06 '17 at 14:19
  • These values into the Json are number fields. Is possible to store these values ad integer or float into DynamoDb? – Federico Mar 06 '17 at 14:21
  • Updated the answer to set the Rh and Temp as Number data type (which includes integer and floats). – notionquest Mar 06 '17 at 14:23
  • Same error: * InvalidParameterType: Expected params.Item['Ut'].N to be a string * InvalidParameterType: Expected params.Item['Temp'].N to be a string * InvalidParameterType: Expected params.Item['Rh'].N to be a string. This is the json that trigger the lambda: { "Id": "Id", "Ut": 1488810488, "Temp": 22.6, "Rh": 57.08 } – Federico Mar 06 '17 at 14:31
  • What is the hash key and sort key of the table and its data type definition? – notionquest Mar 06 '17 at 14:40
  • Hash key: Id as String. Sort Key: Ut as number – Federico Mar 06 '17 at 14:41
  • Solved! I pass a json with a string and then DynamoDB converts itself the values according to its type. Thanks to http://stackoverflow.com/questions/34743527/dynamodb-integer-can-not-be-converted-to-an-string – Federico Mar 06 '17 at 16:00
  • This code worked for me after I added this region for the aws sdk: AWS.config.update({ region: 'ap-southeast-2' }); – Nida Sep 09 '20 at 01:30
6

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)}`);
    }  
};
PersianIronwood
  • 639
  • 8
  • 19
  • This shorter syntax looks great, but it looks like you're losing the ability to send standard http errors. As seen in [this other answer](https://stackoverflow.com/a/39936210/4802021). – Clément Cardonnel Jun 21 '23 at 08:12