Add an API to Delete a Note
Finally, we are going to create an API that allows a user to delete a given note.
Add the Function
Create a new file in packages/functions/src/delete.ts
and paste the following.
import { Resource } from "sst";
import { Util } from "@notes/core/util";
import { DynamoDBClient } from "@aws-sdk/client-dynamodb";
import { DeleteCommand, DynamoDBDocumentClient } from "@aws-sdk/lib-dynamodb";
const dynamoDb = DynamoDBDocumentClient.from(new DynamoDBClient({}));
export const main = Util.handler(async (event) => {
const params = {
TableName: Resource.Notes.name,
Key: {
userId: "123", // The id of the author
noteId: event?.pathParameters?.id, // The id of the note from the path
},
};
await dynamoDb.send(new DeleteCommand(params));
return JSON.stringify({ status: true });
});
This makes a DynamoDB delete
call with the userId
& noteId
key to delete the note. We are still hard coding the userId
for now.
Add the Route
Let’s add a new route for the delete note API.
Add the following below the PUT /notes{id}
route in infra/api.ts
.
api.route("DELETE /notes/{id}", "packages/functions/src/delete.main");
Deploy Our Changes
If you switch over to your terminal, you will notice that your changes are being deployed.
You should see that the new API stack has been deployed.
✓ Deployed:
StorageStack
ApiStack
ApiEndpoint: https://5bv7x0iuga.execute-api.us-east-1.amazonaws.com
Test the API
Let’s test the delete note API.
In a previous chapter we tested our create note API. It should’ve returned the new note’s id as the noteId
.
Run the following in your terminal.
$ curl -X DELETE https://5bv7x0iuga.execute-api.us-east-1.amazonaws.com/notes/<NOTE_ID>
Make sure to replace the id at the end of the URL with the noteId
from before.
Here we are making a DELETE request to the note that we want to delete. The response should look something like this.
{"status":true}
Commit the Changes
Let’s commit and push our changes to GitHub.
$ git add .
$ git commit -m "Adding the API"
$ git push
So our API is publicly available, this means that anybody can access it and create notes. And it’s always connecting to the 123
user id. Let’s fix these next by handling users and authentication.
For help and discussion
Comments on this chapter