7

I have a DynamoDB table with columns and primary key as ipAddress:

  • ipAddress
  • visits

I am fetching the IP address of the user from my react website and inserting it to DynamoDB via a Lambda function and API Gateway POST request.

If the IP address coming from the React website is already present in the DynamoDB, then increment the value in visits column. If not, then create a new record with the new IP address and visits = 1. I tried using ConditionExpression but to no avail.

So far, I am only inserting the ipAddress using Lambda. Below is my Lambda function in NodeJS:

const AWS = require("aws-sdk");
const documentClient = new AWS.DynamoDB.DocumentClient();

exports.handler = async event => {
  const { ipAddress} = JSON.parse(event.body);
  const params = {
    TableName: "ipAddress",
    Item: {
      ipAddress: ipAddress,
    }
  };

  try {
    const data = await documentClient.put(params).promise();
    const response = {
      statusCode: 200,
    };
    return response;
  }
  catch (e) {
    return {
      statusCode: 500,
      body: JSON.stringify(e)
    };
  }

};
Rishab Gupta
  • 561
  • 3
  • 17

1 Answers1

15

We need to use update-item rather than put-item, both creates a record if record doesn't exist. But update-item accepts UpdateExpression to help us update an existing attribute.

UpdateExpression: "SET visits = if_not_exists(visits, :initial) + :num"

if_not_exists helps to use initial value for the first time when attributes visits doesn't exist.

docClient.update(
  {
    TableName: "ipAddress",
    Key: {
      ipAddress: ipAddress,
    },
    UpdateExpression: "SET visits = if_not_exists(visits, :initial) + :num",
    ExpressionAttributeValues: {
      ":num": 1,
      ":initial": 0,
    },
  },
  function (error, result) {
    console.log("error", error, "result", result);
  }
);
Balu Vyamajala
  • 9,287
  • 1
  • 20
  • 42