Skip to content

Instantly share code, notes, and snippets.

@antstanley
Created February 16, 2021 11:05
Show Gist options
  • Save antstanley/4f5fc24681bc868f0ce2113b220a48b1 to your computer and use it in GitHub Desktop.
Save antstanley/4f5fc24681bc868f0ce2113b220a48b1 to your computer and use it in GitHub Desktop.
Dynamically build update parameters required for the DynamoDB Client. Just pass a JSON object of the fields you want to update and get the UpdateExpression, ExpressionAttributeNames and ExpressionAttributeValues returned.
function mapToObject (processMap) {
const returnObject = {}
for (const [key, value] of processMap) {
returnObject[key] = value
}
return returnObject
}
function randomString (stringLength) {
const chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz'
let randomstring = ''
for (let i = 0; i < stringLength; i++) {
const rnum = Math.floor(Math.random() * chars.length)
randomstring += chars.substring(rnum, rnum + 1)
}
return randomstring
}
function buildUpdateExpression (item, parent, expressionMap, attributeNameObj) {
for (const index in item) {
if (typeof item[index] === 'object') {
if (Array.isArray(item[index])) {
const tempArray = item[index]
// console.log(tempArray)
const identifier = `#${randomString(4)}`
// attributeNameObj[identifier] = index
for (let i = 0; i < tempArray.length; i++) {
const indexIdentifier = `${identifier}[${i}]`
attributeNameObj[identifier] = index
const key = parent
? `${parent}.${indexIdentifier}`
: `${indexIdentifier}`
if (typeof tempArray[i] === 'object') {
buildUpdateExpression(
tempArray[i],
key,
expressionMap,
attributeNameObj
)
} else {
expressionMap.set(key, tempArray[i])
}
}
} else {
const identifier = `#${randomString(4)}`
attributeNameObj[identifier] = index
const key = parent ? `${parent}.${identifier}` : identifier
buildUpdateExpression(item[index], key, expressionMap, attributeNameObj)
}
} else {
const identifier = `#${randomString(4)}`
attributeNameObj[identifier] = index
const key = parent ? `${parent}.${identifier}` : identifier
expressionMap.set(key, item[index])
}
}
}
function buildUpdateParams (item) {
const returnMap = new Map()
const returnObj = {}
buildUpdateExpression(item, null, returnMap, returnObj)
let strUpdateExpression = 'SET'
const mapExpressionAttributeValues = new Map()
for (const [key, value] of returnMap.entries()) {
const variableidentifier = randomString(5)
strUpdateExpression += ` ${key} = :${variableidentifier},`
mapExpressionAttributeValues.set(`:${variableidentifier}`, value)
}
return {
UpdateExpression: strUpdateExpression.slice(
0,
strUpdateExpression.length - 1
),
ExpressionAttributeNames: returnObj,
ExpressionAttributeValues: mapToObject(mapExpressionAttributeValues)
}
}
export default buildUpdateParams
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment