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 Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read more →

Top comments (0)

Image of Docusign

🛠️ Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more