Update DynamoDB Item with TypeScript

June 2, 2022

1 min read

Update DynamoDB Item with TypeScript
Watch on YouTube

My app has a table with users, and to update a user with a given id, I have the updateUser function. The second parameter takes an object with fields for the update.

export const updateUser = (id: string, params: Partial<User>) => {
  return documentClient
    .update({
      ...getUserItemParams(id),
      ...getUpdateParams(params),
    })
    .promise()
}

To simplify interactions with DynamoDB, I have a handful of helpers.

The getUpdateParams function takes an object with fields and returns UpdateExpression, ExpressionAttributeNames, and ExpressionAttributeValues, which we need to pass to the document client to update the item.

export const getUpdateParams = (params: { [key: string]: any }) => ({
  UpdateExpression: `set ${Object.entries(params)
    .map(([key]) => `#${key} = :${key}, `)
    .reduce((acc, str) => acc + str)
    .slice(0, -2)}`,

  ExpressionAttributeNames: Object.keys(params).reduce(
    (acc, key) => ({
      ...acc,
      [`#${key}`]: key,
    }),
    {}
  ),

  ExpressionAttributeValues: Object.entries(params).reduce(
    (acc, [key, value]) => ({
      ...acc,
      [`:${key}`]: value,
    }),
    {}
  ),
})

I have a function like getUserItemParams for every table. It returns an object we need to get, update or delete an item.

export const getUserItemParams = (id: string) => ({
  TableName: tableName.users,
  Key: { id },
})