Home > front end >  Lambda function not pushing data into DynamoDB table
Lambda function not pushing data into DynamoDB table

Time:12-07

I'm running a NodeJS lambda function which is triggered by API Gateway.

My goal is to push the data and then send a status response. I think the lambda stops running before the insertData function finishes its execution, because sometimes it works but in most requests it doesn't.

Could someone lend a hand on this?

Here is my code:


// Set a table name that we can use later on
const tableName = "InterestRates"

// Load the AWS SDK for Node.js
var AWS = require('aws-sdk');
// Set the region 
AWS.config.update({region: 'us-east-1'});

// Create the DynamoDB service object
var ddb = new AWS.DynamoDB({apiVersion: '2012-08-10'});
 
exports.handler = async (event) => {
    // TODO implement
    console.log(">>> Running LoanInterestRates")
    
    if(event['resource'] == '/rates'){
        if(event.httpMethod === 'POST'){
            return newRate(event);
        }
    }     
}; 

function insertData(params){
    let status;
    // Call DynamoDB to add the item to the table
    ddb.putItem(params, function(err, data) {
      if (err) {
        status = "Error";
      } else {
        status = "Success";
      } 
    });  
    return status
}

function newRate (event){ 
    const newRate = JSON.parse(event.body);
    var params = {
      TableName: 'InterestRates',
      Item: {
        'termlength' : {N: newRate["length"]},
        'InterestRate': {S: newRate["rate"]}
      }
    }; 
    
     let addNewRate = insertData(params);
     
    
     return  {
        statusCode: 200,
        body: JSON.stringify({ 
            response: addNewRate 
        })
   }
}

I also tried using Async/Await but it didn't work.

CodePudding user response:

You lambda function is Async but your code is not. You need to await the completion of your function newRate which in turn should also await the function inserData which should also await your DDB request.

I would advise you to do one of two things:

  1. Learn how JS Async nature works and ensure you understand when you need to await.
  2. Use a synchronous programming language like Python/Boto3 where you will not run into such issues.
  • Related