DEV Community

Cover image for Update DynamoDB Item with TypeScript
Radzion Chachura
Radzion Chachura

Posted on • Originally published at radzion.com

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()
}
Enter fullscreen mode Exit fullscreen mode

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,
    }),
    {}
  ),
})
Enter fullscreen mode Exit fullscreen mode

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 },
})
Enter fullscreen mode Exit fullscreen mode

Image of Datadog

The Future of AI, LLMs, and Observability on Google Cloud

Datadog sat down with Google’s Director of AI to discuss the current and future states of AI, ML, and LLMs on Google Cloud. Discover 7 key insights for technical leaders, covering everything from upskilling teams to observability best practices

Learn More

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay