Hey Everyone,
In this article, we will learn about how we can perform CRUD operations in Node.js using DynamoDB.
What is DynamoDB?
DynamoDB is a NoSQL database offered by Amazon Web Services (AWS). It is a fully managed, serverless, key-value NoSQL database designed to run high-performance applications at any scale.DynamoDB offers built-in security, continuous backups, in-memory caching, and data import and export tools.
Let’s start by creating a node application and installing dependencies.
Create a folder and name it CRUD With DynamoDB. Open the folder with Visual Studio Code. Once inside the VS Code, open the terminal.
Create a package.json file by running:
npm init -y
Once created, Execute the following command to install express, aws-sdk dependencies in your node js app:
npm i express aws-sdk
Now we have to create a table from the AWS DynamoDB console at https://console.aws.amazon.com/dynamodb/.
Click on the create table button and enter the table name and partition key as shown below image and click on the create table button.
Also, you can create a table using the below code:
var AWS = require("aws-sdk"); AWS.config.update({ region: "us-east-1", endpoint: "http://localhost:7051" }); var client = new AWS.DynamoDB(); var documentClient = new AWS.DynamoDB.DocumentClient(); var tableName = "user"; var params = { TableName: tableName, KeySchema: [ { AttributeName: "id", KeyType: "HASH"}, //Partition key ], AttributeDefinitions: [ { AttributeName: "id", AttributeType: "S" } ] }; client.createTable(params, function(tableErr, tableData) { if (tableErr) { console.error("Error JSON:", JSON.stringify(tableErr, null, 2)); } else { console.log("Created table successfully!"); } });
Now create an index.js file, So go to your app root directory and create it and put the below code inside it:
const express = require("express"); const app = express(); const port = 7051; const userRoute = require("./userRoute"); app.use(express.json()); app.use("/", userRoute); app.listen(port, () => { console.log("port is running at new : ", port); });
Create an userRoute.js file in your root directory and put the below code inside it:
const express = require("express"); const router = express.Router(); const AWS = require('aws-sdk'); const { v4: uuid_v4 } = require('uuid'); AWS.config.update({ region: "us-east-1" }); const dynodata = new AWS.DynamoDB.DocumentClient(); router.get("/user", async (req, res) => { var params = { TableName: "user" }; dyno = await dynodata.scan(params).promise(); res.json({ message: "User get successfully", dyno }); }); router.post("/user", async (req, res) => { if (!(req.body.username && req.body.age && req.body.email)) { return res.json("Enter name, age and email...."); } const reEmail = /^(([^<>()[\]\.,;:\s@\"]+(\.[^<>()[\]\.,;:\s@\"]+)*)|(\".+\"))@(([^<>()[\]\.,;:\s@\"]+\.)+[^<>()[\]\.,;:\s@\"]{2,})$/i; if (!reEmail.test(req.body.email)) { return res.json(401, { message: "Please enter a valid email", }); } let dynoEmail = await getData("email", req.body.email.toLowerCase().trim()); if (dynoEmail.Items.length != 0) { return res.json(401, { message: "Email already exists in our database. please choose a different email address" }) } var data = req.body; data.id = uuid_v4() const params = { TableName: "user", Item: data } return await dynodata.put(params).promise().then(() => { res.json({ message: "User created successfully", data }); } , error => { console.error('There is an error saving user: ', error) }) }); router.put("/user/:userId", async (req, res) => { const reEmail = /^(([^<>()[\]\.,;:\s@\"]+(\.[^<>()[\]\.,;:\s@\"]+)*)|(\".+\"))@(([^<>()[\]\.,;:\s@\"]+\.)+[^<>()[\]\.,;:\s@\"]{2,})$/i; if (!reEmail.test(req.body.email)) { return res.json(401, { message: "Please enter a valid email", }); } var jobParams = { TableName: "user", Key: { id: req.params.userId, }, UpdateExpression: "set email = :e,username =:un, age=:g", ExpressionAttributeValues: { ":e": req.body.email, ":un": req.body.username, ":g": req.body.age }, ReturnValues: "UPDATED_NEW", }; let dyno = await dynodata.update(jobParams).promise(); res.json({ message: "User updated successfully", dyno }); }) router.delete("/user/:userId", async (req, res) => { let params = { TableName: "user", Key: { id: req.params.userId }, }; let dyno = await dynodata.delete(params).promise(); return res.json(200, { message: "User is deleted" }) }); let getData = async (key1, value) => { const params = { TableName: "user" } if (key1 == "email") { params.FilterExpression = `#email = :value`; params.ExpressionAttributeNames = { "#email": "email" } params.ExpressionAttributeValues = { ":value": value } } db = await dynodata.scan(params).promise(); return db; } module.exports = router;
OUTPUT:
Create User :
GetUser :
Update User:
Delete User:
Also check, How to run Cron Jobs in Node.js?