Gaurav Shukla
Gaurav Shukla

Reputation: 1284

CRUD operations using DynamoDB with expressjs (node js)

I am trying to create a route which will perform some CRUD operations on DynamoDB. At high level , it can be understood as :

  1. The node js server application is running .(i.e. command 'node server.js' is being triggered)
  2. The user uses POSTMAN of chrome browser to do route requests.
  3. The user does a GET request for 'http://localhost:8080/listtablesofdynamodb'.
  4. The specific route connected with this url gets hit which should do dynamodb specific activity. (like connecting to dynamodb ,fetching table names and showing it in callback method.)

the reason I am asking this question is because I could not find any relevant tutorial of how to do dynamodb activity by using express js of node. All I could find is console applications on aws website which seems not useful for me. Any kind of help is highly appreciated.

Upvotes: 5

Views: 5647

Answers (2)

Gaurav Shukla
Gaurav Shukla

Reputation: 1284

fortunately, I could manage to use aws-sdk in my route. the solution have two stages:

  1. Run the code in your aws account's EC2 instance and attach an IAM role which allows the ec2 instance to talk to dynamodb. (in this way you don't need to hard-code access key in your code) see this article.
  2. can take reference of the below code for initial code scaffolding.

`

var express = require('express');
var router = express.Router();
var AWS = require("aws-sdk");
AWS.config.update({
      region: "us-west-2",
      endpoint: "dynamodb endpoint specific to your aws account"
});
var dynamodb = new AWS.DynamoDB();
var params = {
      ExclusiveStartTableName: "stringvalue",
      Limit: 10
};
/* GET users listing. */
router.get('/', function (req, res) {
      console.log("entered into dynadb route");
      dynamodb.listTables(params, function (err, data) {
            if (err) console.log(err, err.stack); // an error occurred
            else {
                  res.send(data);
            }
      });
});
module.exports = router; 

`

Upvotes: 0

Joe Lloyd
Joe Lloyd

Reputation: 22323

Access key required

All you need to d is make a DynamoDB object to connect too

var ddb = require('dynamodb').ddb({ accessKeyId: '< your_access_key_id >', secretAccessKey: '< your_secret_access_key >' });

put this under your require statements, turn on your server. Then you can just fill out the routes to do the CRUD operations you need.

To test it use

ddb.listTables({}, function(err, res) {console.log(res);});

This will list all the tables in your db.

for full source check here

Best of luck

Upvotes: 2

Related Questions