Search code examples
javascripttypescriptamazon-dynamodb

Dynamodb: Reset request count when month changes, increment when month is the same


I am trying to update the request count field by 1 when the month is the same, but reset it when the month is different. I am hoping that I can achieve this in one operation.

Currently my expression looks as below.

const month = new Date().getMonth().toString();

const command = new UpdateItemCommand({
    TableName: TABLE_NAME,
    Key: {
      accessKey: { S: metadataAccessKey },
    },
    UpdateExpression:
      'SET requestCount = if_not_exists(requestCount, :start) + :incrementValue, activeMonth = :activeMonth',
    ExpressionAttributeValues: {
      ':incrementValue': { N: '1' },
      ':start': { N: '0' },
      ':activeMonth': { N: month },
    },
    ConditionExpression: 'attribute_exists(accessKey)',
    ReturnValues: 'ALL_NEW',
  });

Solution

  • You cannot achieve an if/else in a single request. What you could do is set a condition on the month being the same, and catch a condition failed exception if they're not the same and set new parameters and re-drive the request.