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!

2 Answers 2

20

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.

Sign up to request clarification or add additional context in comments.

10 Comments

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"}
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
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.
These values into the Json are number fields. Is possible to store these values ad integer or float into DynamoDb?
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 }
|
7

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)}`);
    }  
};

1 Comment

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.