2

I am new on node js dynamo db I wrote a node js sdk to fetch one row from a table ona dynamodb. It is fetching data correctly but not immediately for this I got error

My code is below a simple code

var AWS = require("aws-sdk");

var config = function(){

AWS.config.update({region: 'us-east-1'});

// Create the DynamoDB service object
var ddb = new AWS.DynamoDB({apiVersion: '2012-08-10'});

var params = {
  TableName: 'tblConfigs',
  // Key: {
  //   "id" : {S: "1"},
  // }
  ExpressionAttributeValues: {
   ":v1": {
     S: "1"
    }
  },
  FilterExpression: "id = :v1",
};
var v;
var json = ddb.scan(params, function(err, data) {
  if (err) {
    console.log("Error", err);
  } else {
    v = data;
    // console.log(JSON.stringify(data.Item));
   // return JSON.stringify(data.Item);
  }
});
// if(v=="u")
// for(var i=0;)

v = v.Items[0];

// for()

var con = {
    "host": v.endpoint.S,
    "user": v.endpoint.username.S,
    "password": v.endpoint.password.S,
    "database": v.endpoint.database_name.S
};

return con;
}

And I got the below error

> config()
TypeError: Cannot read property 'Items' of undefined
    at config (repl:31:7)

as v is undefined so it is giving the error but v is not undefined when I execute the code in node console it first time gave undefined next time it gave value

like below

> v
{ Items:
   [ { password: [Object],
       stage: [Object],
       username: [Object],
       id: [Object],
       endpoint: [Object],
       database_name: [Object] } ],
  Count: 1,
  ScannedCount: 1 }

how can I fetch the row immediately not after some time? IS there any good way in dynamodb I tried, get, getItem, scan, query all are giving data correctly but not immediately...Please suggest

1 Answer 1

2

You are missing one important thing: Javascript execution is asynchronous. As long as you are not using async/await syntax you have to "play" with callbacks like this:

var ddb = new AWS.DynamoDB({ apiVersion: '2012-08-10' });

function loadConfig(callback) {
    var params = {
        TableName: 'tblConfigs',
        ExpressionAttributeValues: {
            ':v1': {
                S: '1'
            }
        },
        FilterExpression: 'id = :v1'
    };

    ddb.scan(params, function (error, data) {
        if (error) {
            callback(error);
        } else {
            var item = data.Items[0];
            callback(null, {
                'host': item.endpoint.S,
                'user': item.endpoint.username.S,
                'password': item.endpoint.password.S,
                'database': item.endpoint.database_name.S
            });
        }
    });
}

loadConfig(function (error, configuration) {
    if (error) {
        console.log(error);
    } else {
        // Your connection logic (JUST AN EXAMPLE!)
        var connection = mysql.connect({
            host: configuration.host,
            user: configuration.user,
            password: configuration.password,
            database: configuration.database
        })
    }
});

Btw. storing database configurations in DynamoDB isn't a good solution, i would recommend to check AWS Systems Manager Parameter Store.


Edit

To give you a short example how the async/await syntax looks like

var ddb = new AWS.DynamoDB({ apiVersion: '2012-08-10' });

const loadConfig = async () => {
    const { Items } = await ddb.scan({
        TableName: 'tblConfigs',
        ExpressionAttributeValues: {
            ':v1': {
                S: '1'
            }
        },
        FilterExpression: 'id = :v1'
    }).promise();

    const item = Items[0];
    return {
        'host': item.endpoint.S,
        'user': item.endpoint.username.S,
        'password': item.endpoint.password.S,
        'database': item.endpoint.database_name.S
    };
};
Sign up to request clarification or add additional context in comments.

2 Comments

Please debug by your own... console.log(item); Its very hard to judge now without knowing the response
(node:34792) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'S' of undefined aernal/process/next_tick.js:228:7) (node:34792) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1) (node:34792) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.