This code is written in AWS V3 SDK.
It can get non-existing error, get delete item, and best of all, this code can avoid race condition and delete item appropriately in DynamoDB.
import {
DynamoDBClient,
DeleteItemCommand,
} from "@aws-sdk/client-dynamodb";
const client = new DynamoDBClient({});
export const handler = async (event, context) => {
let statusCode = 200;
let body={};
const headers = {
"Content-Type": "application/json",
};
let eventBody = JSON.parse(event.body);
try{
const input = {
"Key": {
"primaryKey": {
"S": eventBody.primaryKey,
},
},
"TableName": "yourTableName",
"ConditionExpression": 'attribute_exists(primaryKey)',
"ReturnValues": "ALL_OLD",
};
const command = new DeleteItemCommand(input);
const response = await client.send(command);
body=response.Attributes;//you can get the delete item
}
catch(error){
console.log(error);
if (error.name === 'ConditionalCheckFailedException') {
statusCode = 409;
body.error = error;
body.message='Item was already deleted';
}
else {
statusCode = 500;
body.error = error;
body.message='Internal server error';
}
}
return {
statusCode,
body: JSON.stringify(body),
headers,
};
};