Created
May 2, 2019 18:02
-
-
Save robzhu/2f4cc225a5b8aa0ddf58832c37b3954d to your computer and use it in GitHub Desktop.
This file contains hidden or 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
// helper function to return the error in a promise | |
async function updateWithErrorWrapper(params) { | |
return new Promise(resolve => { | |
DynamoDB.update(params, (err, data) => { | |
resolve({ err, data }); | |
}); | |
}); | |
} | |
async function conditionalRemoveFriendByValue(friendName) { | |
const Key = { id: "1234" }; | |
// fetch the document | |
let result = await DynamoDB.get({ | |
TableName, | |
Key | |
}).promise(); | |
// find the index | |
let indexToRemove = result.Item.friends.indexOf(friendName); | |
if (indexToRemove === -1) { | |
// element not found | |
return false; | |
} | |
// remove-by-index IFF the attribute contains the element we want to remove. | |
const { err, data } = await updateWithErrorWrapper({ | |
TableName, | |
Key, | |
UpdateExpression: `REMOVE friends[${indexToRemove}]`, | |
ConditionExpression: `friends[${indexToRemove}] = :valueToRemove`, | |
ExpressionAttributeValues: { | |
":valueToRemove": friendName | |
} | |
}); | |
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