Search code examples
amazon-dynamodb

How do I increment counter field by 1 using UpdateCommand


I'm trying to make a rate limiter and I'm having trouble finding documentation on UpdateCommand. Right now I'm trying to increment the counter field by 1 everytime I make a request with the same ip address.

enter image description here https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/classes/_aws_sdk_lib_dynamodb.updatecommand-1.html

Here is what I tried

const command = new UpdateCommand({
    TableName: tableName,
    Key: {
        ipAddr: sourceIp
    },
    UpdateExpression: "set counter = Add :counter counter",
    ExpressionAttributeValues: {
        ":counter": 1,
    },
    ReturnValues: "ALL_NEW",
});


Solution

  • This should be it:

    const command = new UpdateCommand({
        TableName: tableName,
        Key: {
            ipAddr: sourceIp
        },
        UpdateExpression: "ADD counter :counter",
        ExpressionAttributeValues: {
            ":counter": 1,
        },
        ReturnValues: "ALL_NEW",
    });