I made this using dynamo DB client:
updateItem(item: { [key: string]: any }) {
const marshaledItem = marshall(item, { removeUndefinedValues: true, });
const marshaledItemKeys = Object.entries(marshaledItem);
const params: UpdateItemInput = {
TableName: this.tableName,
UpdateExpression: 'set',
ExpressionAttributeNames: {},
ExpressionAttributeValues: {},
Key: marshall({ pk: item.pk, sk: item.sk })
};
marshaledItemKeys.forEach(([key, value] ) => {
if (key === 'sk' || key === 'pk') return;
params.UpdateExpression += ` #${key} = :${key},`;
params.ExpressionAttributeNames[`#${key}`] = key;
params.ExpressionAttributeValues[`:${key}`] = value;
})
params.UpdateExpression = params.UpdateExpression.slice(0, -1);
console.log('REVEAL YOURSELF, YOU MIGHTY BUG: ', params);
return this.dynamoDbClient.send(new UpdateItemCommand(params));
}
This worked really well for me. Marshall and unmarshall are part of:
import { marshall, unmarshall } from '@aws-sdk/util-dynamodb';
If I pass values that are undefined
it will remove those values from the query. If I keep them null
it will overwrite them with null
Here is an example how I use it:
async updatePatient(data: PutPatientData): Promise<DBPatient> {
const {
pk,
sk,
databaseId,
betterPatientId,
clinicientPatientId,
latestClinicientCaseId,
firstName,
lastName,
email,
birthday,
gender,
phone,
} = data;
if (!pk && !databaseId) throw Error('Please provide PK or databaseId');
if (!sk && !betterPatientId) throw Error('Please provide SK or betterPatientId');
const patientRequestData = {
pk: pk || `DATABASE#${databaseId}`,
sk: sk || `PATIENT#${betterPatientId}`,
itemType: 'Patient',
lastUpdatedAt: DateTime.now().toString(),
latestClinicientCaseId: latestClinicientCaseId || undefined,
clinicientPatientId: clinicientPatientId || undefined,
firstName: firstName || undefined,
lastName: lastName || undefined,
email: email || undefined,
birthday: birthday || undefined,
gender: gender || undefined,
phone: phone || undefined,
betterPatientId: betterPatientId || undefined,
} as DBPatient;
// Composite key
if (email && birthday) patientRequestData['itemId'] = `PATIENT#${email}#${birthday}`;
console.log('PATIENT UPDATE', patientRequestData)
return this.updateItem(patientRequestData).then(() => patientRequestData);
}