sst.dev icon indicating copy to clipboard operation
sst.dev copied to clipboard

batchWrite function doesnt work

Open SumayaG opened this issue 7 years ago • 1 comments

Hi @jayair,

I was trying to add a delete all button to delete all the notes that a user has created. I think it is a great thing to have when a user wants to delete all his notes. The problem is that batchWrite doesn't seem to work and I get a 404 error "ValidationException: The provided key element does not match the schema". As you can see in the code below, I am giving only the userId as the key. If, I give the noteId as well then the function correctly deletes that individual note. But, that is exactly same as a regular single delete. I don't want to do that as that is not efficient for a huge lists. What am I doing wrong? Can you try the following function at your end?

export async function mainDeleteAll(event, context, callback) {
  const params = {
    RequestItems: {
      notes: [
        {
          
          DeleteRequest: {
            Key: {
              userId: event.requestContext.identity.cognitoIdentityId
            }
          }
        }
      ]
    }
  };

  try {
    const result = await dynamoDbLib.call('batchWrite', params);
    callback(null, success({ status: true }));
  } catch (e) {
    console.log(e);
    callback(null, failure({ status: false }));
  }
}

//serverless.yml function

deleteAll:
    handler: delete.mainDeleteAll
    events:
      - http:
          path: notes
          method: delete
          cors: true
          authorizer: aws_iam

//test-event.json

{
  "requestContext": {
    "identity": {
      "cognitoIdentityId": "*************"
    }
  }
}

SumayaG avatar Mar 11 '18 00:03 SumayaG

@SumayaG DynamoDB currently does not support deleting all range keys given a hash key. Consider table (userId : Hash Key, noteId: Range Key), you cannot delete all rows given a userId.

BatchWrite is simply a convenient way to run multiple queries at once. For example, get all noteIds for a userId, and then run batch write with each userId-noteId pair. See docs: https://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_BatchWriteItem.html

fwang avatar Mar 14 '18 01:03 fwang