This post will use the code samples from this API on Github to demonstrate how to insert, update, delete & fetch data from AWS DyanmoDB using Typescript. In summary this post is a AWS DynamoDB with Typescreipt how-to. The goal of this post is simply to showcase how to do these operations and not to dwell deep into the theory of DynamoDB or talk about the cost effectiveness of using it if you are already invested into the AWS tech stack. The Github repo talked about in this post is cptdanko/node_typescript_crud_notes (github.com). Do keep in mind that, the repo uses two storage solutions. The default storage solution is filestorage using node-localStorage and AWS DynamoDB is the other solution. In the presence of a certain header in the request determines the storage mechanism the repo uses.
Pre-requisite: AWS setup
In this post, I will not focus on how to setup your NodeJS API to use AWS services. An online search on this topic would lead to the official AWS docs which do a great job of explaining how to setup and work with the AWS SDK.
Also, be mindful of the fact that you would also need two environment variables e.g.
export AWS_ACCESS_KEY_ID="your-access-key"
export AWS_SECRET_ACCESS_KEY="your-secret-key"
There are many ways in which you can get your NodeJS API use these environment variables. One way wold be to export them in your profile if you are working on a Unix based OS. In my case, I was working on on Ubuntu and after executing echo $0 in the terminal, I realised I was working with a bash shell. Hence, I edited my bashrc file via vim ~/.bashrc and added the above lines to export the key_id and secret access key and it worked.
AWS DynamoDB with Typescript How-To …
To illustrate the concepts, here, I will be using the models of this repo that focus on building a REST API to CRUD notes to the DB. Here’s the model for the notes
export interface Note {
date: Date;
text: string;
user: {};
note_id: string | null;
}
A class to persist data to AWS DynamoDB
class DB {
documentClient = new AWS.DynamoDB.DocumentClient(this.regionParam);
}
How to save data to DynamoDB with Typescript
This would be fairly straightforward to you if you have worked with a document DB such as MongoDB before. To save notes, add this method to the class
saveNote(note: Note) {
const params = {
TableName: NOTES_TABLE,
Item: note
};
this.getNotesFromAWS().then((data:ScanOutput) => {
data.Items
});
this.documentClient.put(params, AWSCallback);
}
How to update data in DynamoDB with Typescript
To update an object (e.g. note) by id, add this method to the class.
async updateNote(note_id: string, note: Note): Promise<UpdateItemOutput> {
const existingNote = (await this.getNoteFromAWS(note_id)).Item;
const params = {
TableName: NOTES_TABLE,
Key: {
'note_id': note_id
},
UpdateExpression: "set #d1 = :date, #t1 = :t, #u1 = :user",
ExpressionAttributeValues: {
":date": note.date ?? existingNote?.date,
":t": note.text ?? existingNote?.text,
":user": note.user ?? existingNote?.user
},
ExpressionAttributeNames: {
"#d1": "date",
"#t1": "text",
"#u1": "user"
}
};
return this.documentClient.update(params).promise();
}
How to retrieve data from DynamoDB with Typescript
Retrieving data (e.g. all notes) from DynamoDB is one of the easiest things to do with Typescript. All you need is the tableName from which you need to get the data. Add the method below to the class.
getNotes(): Promise<ScanOutput>{
const params = {
TableName: NOTES_TABLE
};
return this.documentClient.scan(params).promise();
}
How to delete data from DynamoDB with Typescript
If you need to delete an object by a specific id, you will need to create an object where you need to specify a table name and a key object with the name of the column and the value.
deleteNote(note_id: string): Promise<DeleteItemOutput> {
const params = {
TableName: NOTES_TABLE,
Key: {
'note_id': note_id
}
};
return this.documentClient.delete(params).promise();
}
Summary
This post focuses on the AWS DynamoDB with Typescript How-To and demonstrates via code samples of a repository on Github. The repo is open source and I would appreciate if you can find the timecontribute to it.
If you find any of my posts useful and want to support me, you can buy me a coffee 🙂
https://www.buymeacoffee.com/bhumansoni
Have a read of some of my other posts on AWS
Deploy NodeJS, Typescript app on AWS Elastic beanstalk – (mydaytodo.com)
How to deploy spring boot app to AWS & serve via https – My Day To-Do (mydaytodo.com)
Some of my other posts on Javascript …
What is Javascript event loop? – My Day To-Do (mydaytodo.com)
How to build a game using Vanilla Javascript – My Day To-Do (mydaytodo.com)
Vanilla Javascript: Create Radio Buttons (How-To) – Bhuman Soni (mydaytodo.com)
Java Spring Boot & Vanilla Javascript solution – My Day To-Do (mydaytodo.com)
Vanilla Javascript: Create Radio Buttons (How-To) – Bhuman Soni (mydaytodo.com)
While you are here, maybe try one of my apps for the iPhone.
0 Comments