Created
May 2, 2019 18:10
-
-
Save robzhu/9fa1dbacd4c4e2ec0457ce4bdda2987a to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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