Skip to content

Instantly share code, notes, and snippets.

@alanzhaonys
Last active July 5, 2023 13:52
Show Gist options
  • Save alanzhaonys/2b24fb051bb63f86c8b85343b3746263 to your computer and use it in GitHub Desktop.
Save alanzhaonys/2b24fb051bb63f86c8b85343b3746263 to your computer and use it in GitHub Desktop.
Reusable DynamoDb Function to Update Multiple Fields at Once
import { DateTime } from "luxon";
import {
AttributeValue,
DynamoDBClient,
QueryCommand,
UpdateItemCommand,
} from "@aws-sdk/client-dynamodb";
const dynamoDBClient = new DynamoDBClient({});
interface UserFields {
[key: string]: string | boolean | number;
}
export const updateUserFields = async (
userId: string,
fields: UserFields
): Promise<boolean> => {
const currentDateTime = DateTime.now();
const now = currentDateTime.toFormat("MM/dd/yy hh:mm:ss a");
const userTable = "users";
try {
// Construct update expression
const updateExpressions = [];
Object.keys(fields).forEach((field: string) => {
updateExpressions.push(`#${field} = :${field}`);
});
updateExpressions.push("#updated_at = :updated_at");
const updateExpression = "SET " + updateExpressions.join(", ");
const expressionAttributeNames: Record<string, string> = {};
const expressionAttributeValues: Record<string, AttributeValue> = {};
// Construction attribute names and values
Object.keys(fields).forEach((field: string) => {
const value = fields[field];
const namePlaceholder = `#${field}`;
const valuePlaceholder = `:${field}`;
expressionAttributeNames[namePlaceholder] = field;
if (typeof value === "boolean") {
expressionAttributeValues[valuePlaceholder] = { BOOL: value };
} else if (typeof value === "number") {
expressionAttributeValues[valuePlaceholder] = { N: value.toString() };
} else if (typeof value === "string") {
expressionAttributeValues[valuePlaceholder] = { S: value };
}
// Add support for other data types...
});
expressionAttributeNames["#updated_at"] = "updated_at";
expressionAttributeValues[":updated_at"] = { S: now };
const updateCommand = new UpdateItemCommand({
TableName: userMetadataTableName,
Key: { user_id: { S: userId } },
UpdateExpression: updateExpression,
ExpressionAttributeNames: expressionAttributeNames,
ExpressionAttributeValues: expressionAttributeValues,
});
await dynamoDBClient.send(updateCommand);
return true;
} catch (error: any) {
// Your own error handling here...
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment