Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Connecting Node.js app to DynamoDB

So I have searched the past 2 days for documentation, examples, or anything that can specifically show me how to successively set a connection between my node.js app and AWS DynamoDB. I'm fairly new to both but it appears there's a lot more documentation for Java, PHP, and .NET.

Even after following all the directions on the documentation AWS provides, I cannot seem to get my application to work. To test if I configured everything correctly, I tried uploading a text file to S3, which worked just fine.

Any thoughts why this may happen? I don't get any errors or successes so I feel like it's not connected but not sure if anyone else out there is familiar with this issue? Thanks!

like image 551
Laurence Rosenzweig Avatar asked Aug 31 '25 18:08

Laurence Rosenzweig


1 Answers

You need to first login to aws account, create a group and a user, after that you will get the Access key ID and Secret access key, which you can download in a csv file.

Then make a table and insert records into that table,and then you can use the below code using your Access key ID, Secret access key, region and the table name.

app.js

let app=require('express')();
let dynamoRoute= require('./dynamo');

app.use('/',dynamoRoute);

app.listen('4000',(err)=>{
    if(err) console.log(err)
    else console.log('server running');
})

module.exports=app;

dynamo.js

let AWS = require('aws-sdk');
let express = require('express');
let router = express.Router();
let config = require('./config/dev');
AWS.config.update({
 "region": "",
 "accessKeyId": "",
 "secretAccessKey": ""
});

let docClient = new AWS.DynamoDB.DocumentClient();
let table = "sports";

router.get('/fetch', (req, res) => {

let spid = '101';
let params = {
    TableName: table,
    Key: {
        spid: spid
    }
};

docClient.get(params, function (err, data) {
    if (err) {
        console.log(err);
        handleError(err, res);
    } else {
        handleSuccess(data.Item, res);
    }
 });
});
function handleError(err, res) {
    res.json({ 'message': 'server side error', statusCode: 500, error: 
    err });
}

function handleSuccess(data, res) {
    res.json({ message: 'success', statusCode: 200, data: data })
}
like image 199
Nayan Patel Avatar answered Sep 02 '25 08:09

Nayan Patel