Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

dynamodb putItem callback function not working

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

exports.handler = async (event) => {

    var note = {};
    note.noteid = new Date().getTime();
    note.content = event.queryStringParameters["content"];

    var res = {};

    const response = {
        statusCode: 200,
        body: JSON.stringify(note),
    };

    var obj = {
        'TableName':'notes',
        'Item': {
          'note_id': {
            S: '2'
          },
          'name': {
            S: 'content'
          }
        },
        'ReturnConsumedCapacity': "TOTAL"
    };

    dynamodb.putItem(obj, function(err,result){
        console.log('function called!!');
        console.log(err);

        return response;
    });

};

My putItem is not working, the callback function is not being called. I have given full access to role of this user, but still function is not getting called.

like image 961
Shiva Burade Avatar asked Jan 15 '19 06:01

Shiva Burade


2 Answers

Another possible reason for this error is because of one using AWS.DynamoDB.DocumentClient() instead of AWS.DynamoDB(); In that case, DocumentClient uses the put method instead of putItem

I kept checking the async and promise code when this was the cause

like image 70
Jonathan Lee Avatar answered Sep 19 '22 19:09

Jonathan Lee


Assume you are using AWS Lambda. Since you are using the async/await pattern, the http response is eventually what async (event) => {} returns. In your case, that is nothing. You called putItem but did not wait for it. async (event) => {} return nothing immediately afterwards. Since the function has returned, your putItem call has no chances to callback.

You should convert the putItem call to promise and await for it. Then handle the result and return the http response.

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

exports.handler = async (event) => {

    var note = {};
    note.noteid = new Date().getTime();
    note.content = event.queryStringParameters["content"];

    var res = {};

    const response = {
        statusCode: 200,
        body: JSON.stringify(note),
    };

    var obj = {
        'TableName':'notes',
        'Item': {
          'note_id': {
            S: '2'
          },
          'name': {
            S: 'content'
          }
        },
        'ReturnConsumedCapacity': "TOTAL"
    };

    try
    {
        var result = await dynamodb.putItem(obj).promise();
        //Handle your result here!
    }
    catch(err)
    {
        console.log(err);
    }
    return response;
};
like image 41
Ricky Mo Avatar answered Sep 20 '22 19:09

Ricky Mo