DynamoDB put item with unique partition key and retry

  async create() {
    const result = await this.create_retry();

    return result;
  }

  async create_retry(retries = 10) {
    let db_params, db_result;

    // A key that should be unique, but we're not sure
    const hopefully_unique_key = random_string();

    db_params = {
      TableName: 'xxx',
      Item: {
        partition_key: hopefully_unique_key,
        other_attribute: other_attribute
      },
      ConditionExpression: 'attribute_not_exists(partition_key)'
    };
    try {
      db_result = await db.client.put(db_params).promise();
    } catch(error) {
      // Retry until the last attempt
      if (retries == 1) {
        throw error;
      }
  
      return await this.create_retry(retries - 1);
    }

    return db_result;
  }

Leave a Comment