Search code examples
aws-lambdaevent-handlingamazon-dynamodbserverless-frameworkaws-sdk-js

Convert Lambda synchronise to async event issue


I am trying to make basic todo app by using Serverless framework. My synchronous lambda function works fine and store my task and taskdetails in the dynamodb table. I decided to convert my synchronous lambda function into async function. And I am testing api by using Postman. But now I have event trigger problem, It does not store my taskDetails, it just store my task only. In my post man I can see event trigger and here is the post-method and this is what I get. I don’t get what I am doing wrong in here. Ps. I am new to Lambda.

This is synchronous lambda function

'use strict'
const AWS = require('aws-sdk');
const uuid = require('uuid');
const dynamoDb = new AWS.DynamoDB.DocumentClient();
module.exports.createTodo = (event, context, callback) => {
  const datetime = new Date().toISOString();
  const data = JSON.parse(event.body);
  const params = {
    TableName: 'todos',
    Item: {
      id: uuid.v1(),
      task: data.task,
      taskDetails: data.taskDetails,
      done: false,
      createdAt: datetime,
      updatedAt: datetime
    }
  };
  dynamoDb.put(params, (error, data) => {
    if (error) {
      console.error(error);
      callback(new Error(error));
      return;
    }
const response = {
      statusCode: 201,
      body: JSON.stringify(data.Item)
    };

    callback(null, response);
  });
}

This is my async and put in try catch, where I got error.

'use strict'
const AWS = require('aws-sdk');
const uuid = require('uuid');

const dynamoDb = new AWS.DynamoDB.DocumentClient();

module.exports.createTodo = async event => {
  const datetime = new Date().toISOString();
  const data = JSON.parse(event.body);
  const params = {
    TableName: 'todos',
    Item: {
      id: uuid.v1(),
      task: data.task,
      taskdetails: data.taskdetails,
      done: false,
      createdAt: datetime,
      updatedAt: datetime
    }
  };

  try {
    let response = await dynamoDb.put(params).promise();
    return {
      statusCode: 200,
      body: JSON.stringify(data),
    }
  } catch (error) {
    console.log(error);
  }
};

Solution

  • In your synchronous code you are using taskDetails where as in async implementation it is taskdetails.

    I am assuming in your get method you are reading data from taskDetails, so your get api is not returning taskDetails in response.

    Go to dynamodb console and check for your id you will be able to see data in taskdetails attribute.