Skip to content

Instantly share code, notes, and snippets.

@robzhu
Created May 2, 2019 18:10
Show Gist options
  • Save robzhu/9fa1dbacd4c4e2ec0457ce4bdda2987a to your computer and use it in GitHub Desktop.
Save robzhu/9fa1dbacd4c4e2ec0457ce4bdda2987a to your computer and use it in GitHub Desktop.
async function conditionalVersionRemoveFriendByValue(friendName) {
const Key = { id: "1234" };
// fetch the document
const document = (await DynamoDB.get({
TableName,
Key
}).promise()).Item;
// find the index
let indexToRemove = document.friends.indexOf(friendName);
let version = document.version;
if (indexToRemove === -1) {
// element not found
return false;
}
// remove-by-index IFF the version field matches
const { err, data } = await updateWithErrorWrapper({
TableName,
Key,
UpdateExpression: `
REMOVE friends[${indexToRemove}]
ADD version :incrementVersionBy
`,
ConditionExpression: `version = :version`,
ExpressionAttributeValues: {
":version": version,
":incrementVersionBy": 1
}
});
if (err) {
if (err.code === "ConditionalCheckFailedException") {
console.error("condition expression failed");
} else {
console.error("unhandled error: " + err);
}
return false;
}
return true;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment