Tuesday, 24 September 2019

AWS Lambda Node Js - Increment value if exist else add element

I want increment value if exist else add element.

+-----------------------+
| id | iteration | data |
+-----------------------+
| 10 |         1 | foo1 |
| 11 |         1 | foo2 |
| 12 |         2 | foo3 |
+-----------------------+

my code:

var AWS = require('aws-sdk');
var documentClient = new AWS.DynamoDB.DocumentClient({'region': 'eu-west-1'}); 
exports.handler = function(event, context, callback) {

var params = {
  Item: {
    id: uuid,
    iteration: 1,
    data: body.data
  },
  TableName: "my-table"
};

documentClient.put(params, function(err, data) {
    if (err) {
      console.log("Error", err);
      const errResponse = {
        statusCode: 500,
        headers: {
          "Access-Control-Allow-Origin": "*"
        },
        body: JSON.stringify({ Error: 500, device : "DynamoDB", detail : err })
      };
      callback(null, errResponse);
    } else {
      console.log("Success", params.Items);
      const response = {
        statusCode: 200,
        headers: {
          "Access-Control-Allow-Origin": "*"
        },
        body: JSON.stringify("thanks")
      };
      callback(null, response);
    }
  });

}

My insert is OK.

I try with:

var params = {
    TableName: "my-table",
    Key:{
        "id": uuid
    },
    UpdateExpression: "set iteration = iteration + :val",
    ExpressionAttributeValues:{
        ":val": 1
    },
    ReturnValues:"UPDATED_NEW"
  };
  documentClient.update(params, function(err, data) {
    if (err) {
        console.error("Unable to update item. Error JSON:", JSON.stringify(err, null, 2));
        const errResponse = {
          statusCode: 500,
          headers: {
            "Access-Control-Allow-Origin": "*"
          },
          body: JSON.stringify({ Error: 500, device : "DynamoDB", detail : err })
        };
        callback(null, errResponse);
    } else {
        console.log("UpdateItem succeeded:", JSON.stringify(data, null, 2));
        const response = {
          statusCode: 200,
          headers: {
            "Access-Control-Allow-Origin": "*"
          },
          body: JSON.stringify("thanks")
        };
        callback(null, response);
    }
  });

Update is OK (increment -> 2)

But I want I want increment value ONLY if exist else ONLY add element. Both methods are asynchronous, how should I do?



from AWS Lambda Node Js - Increment value if exist else add element

1 comment:

  1. Such a very useful article. Very interesting to read this article. I would like to thank you for the efforts you had made for writing this awesome article

    AWS Training Hyderabad/
    AWS Course Hyderabad/
    AWS Training Institutes Hyderabad/
    AWS Online Training Hyderabad/

    ReplyDelete