Mikita Melnikau
Mikita Melnikau

Reputation: 1765

DynamoDB createIfNotExist

In dynamoDB I should create some kind of log information, that has a state that user could change. But it is unnecessary extra information. Main question is:

  1. I have an object:
{
  id: '123',
  log: 'mybestlog',
  state: 'PENDING'
}
  1. I want to create this document object if document with same id not exists.
  2. I want to get back current object and flag, if object with same id exits.

Hope I tell all enough clear.

I tried to do:

      const result: PutItemOutput = await this.dynamodbClient.put({
          TableName: this.config.tableName,
          Item: {
            ...newItem,
            status: statusEnum.PENDING,
            creationDate: moment().toISOString(),
          },
          ConditionExpression: 'attribute_not_exists(id)',
          ReturnValues: 'ALL_NEW',
      })
        .promise()
        .catch((error) => {
          this.logger.error(`### END-ERROR ${methodDescription} | error: ${error}`, metadata);
          throw new InternalServerErrorException(error.stack);
        });

But can't found any Items or flags Exist in response. I got AWS.DynamoDB.PutItemOutput:

      {
        Attributes?,
        ConsumedCapacity?,
        ItemCollectionMetrics?,
      }

Please help me, what the best solution is in my situation.

Upvotes: 0

Views: 126

Answers (1)

Sumit
Sumit

Reputation: 171

you don't get a response with a flag that an item exits in dynamoDB, the way you're thinking.

When you call put operation with that ConditionExpression. The two major outcomes and those that matter for you are:

  1. Your ConditionExpression succeeded and you'll get ALL_NEW values in Attributes Key.
  2. Otherwise you'll get some error. The one that matters for you is ConditionalCheckFailedException which means that ConditionExpression failed and the key already exists.

You'll need to tailor a response yourself accordingly.

Upvotes: 4

Related Questions