我使用 Dynamo DB 客户端制作了这个。
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));
}
这对我来说非常有效。Marshall和unmarshall是的一部分:
import { marshall, unmarshall } from '@aws-sdk/util-dynamodb';
如果我传递的值是
undefined
,它将从查询中删除这些值。如果我保留它们为
null
,它将用
null
覆盖它们。
以下是一个我使用它的示例:
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;
if (email && birthday) patientRequestData['itemId'] = `PATIENT#${email}#${birthday}`;
console.log('PATIENT UPDATE', patientRequestData)
return this.updateItem(patientRequestData).then(() => patientRequestData);
}