I'm stuck because I'm having a problem deleting an element in DynamoDB table with primary key and global secondary index (there is no Sort Key).
I get the following error: "The provided key element does not match the schema"
I am desperate, I also tried to look at the answers of other posts on this site but I could not find anything about the delete.
This is my code:
const AWS = require("aws-sdk");
const dynamo = new AWS.DynamoDB.DocumentClient();
exports.handler = async (event, context) => {
let body;
let statusCode = 200;
const headers = {
"Content-Type": "application/json",
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "DELETE",
};
try {
switch (event.routeKey) {
case "DELETE /fragments/{id}":
await dynamo
.delete({
TableName: "fragment",
Key: {
id: event.pathParameters.id
}
})
.promise();
body = `Deleted fragment ${event.pathParameters.id}`;
break;
default:
throw new Error(`Unsupported route: "${event.routeKey}"`);
}
} catch (err) {
statusCode = 400;
body = err.message;
} finally {
body = JSON.stringify(body);
}
return {
statusCode,
body,
headers
};
};
CodePudding user response:
TL;DR Convert event.pathParameters.id from string to number type.
// convert id from string to number
Key: { id: parseInt(event.pathParameters.id, 10) }
DynamoDB.DocumentClient infers the key schema types from the javascipt types in Key. event.pathParameters.id is a string, but your key schema expects a number, so DynamoDB returns a schema mismatch error.
How do we know event.pathParameters.id is a string? The lambda typings for API Gateway events tell us so:
// APIG event pathParameters
export interface APIGatewayProxyEventPathParameters {
[name: string]: string | undefined;
}
