1
votes

I'm trying to write to a DynamoDB table from a Lambda function. When I test run the function, it returns null, with no error message and nothing is written to the table. The function is below. I have already set up a service role for this function with a permissions policy that allows access to the 'Products' table. I have seen some tutorials mention creating an "AWS Lambda Application", then creating the Lambda function, but I did not think this was necessary for my use.

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

exports.handler = async (event, context, callback) => {

  dynamodb.putItem({
      TableName: "Products",
      Item: {
          "sku": {S: "29574839"},
          "name": {S: "Test Code"}
      }
  }, function(err, data) {
      if (err) {
          console.log(err, err.stack);
          return callback(null, {
              statusCode: '500',
              body: err
          });
      } else {
          return callback(null, {
              statusCode: '200',
              body: 'Adding to table!'
          });
      }
  });

};

I've also tried using document client const docClient = new dynamodb.DocumentClient(); and I get the error: "dynamodb.DocumentClient is not a constructor".

What am I missing here? Thanks!

CloudWatch logs show (I removed the request id): Function logs: START RequestId: Version: $LATEST END RequestId: REPORT RequestId: Duration: 491.07 ms Billed Duration: 500 ms Memory Size: 128 MB Max Memory Used: 87 MB Init Duration: 405.37 ms

1
Did you check the cloudwatch logs? - Nishu Tayal
@NishuTayal I added that to my question. They don't appear to show anything useful. - Nick H

1 Answers

2
votes

Since you are using async handler I think the issue is that your function completes before handler's body has a chance to run.

One way to rectify this is through the use of Promise as shown in AWS docs. For example:

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

exports.handler = async (event, context, callback) => {

    const promise = new Promise(function(resolve, reject) {

      dynamodb.putItem({
          TableName: "Products",
          Item: {
              "sku": {S: "29574839"},
              "name": {S: "Test Code"}
          }
      }, function(err, data) {
          if (err) {
              console.log(err, err.stack);
              return callback(null, {
                  statusCode: '500',
                  body: err
              });
          } else {
              return callback(null, {
                  statusCode: '200',
                  body: 'Adding to table!'
              });
          }
      });
  })

  return promise;   
};

The above changes are exemplary only, thus probably some adjustments will be still needed.