4

I'm building a serverless backend for my current application using dynamoDb as my database. I use aws sam to upload my lambda functions to aws. In addition, I pass all my table names as global variables to lambda (nodejs8.10 runtime) to access them on the process.env object within my lambda function. The problem that I'm facing with this is the following: Whenever I run the batchGetItem method on dynamoDB I have to pass a string as my table name, I cannot dynamically change the table name depending on the global variable:

const AWS = require('aws-sdk');
const dynamodb = new AWS.DynamoDB({region: 'ap-south-1'}, {apiVersion:'2012-08-10'});

const params = {
    RequestItems: {
        //needs to be a string, cannot be a variable containing a string
        'tableName': {
            Keys: [] //array of keys
         }
    }
}
dynamodb.batchGetItem(params, (err, result) => {
// some logic
})

I need to pass the table name as a string, essentially hardcoding the table name into my function. Other DynamoDB operations, like for example the getItem method, accept a key value pair for the table name in the parameter object:

const tableName = process.env.TableName;
const getItemParams = {
   Key: {
        "Key": {
             S: 'some key'
         }
   },
   // table name can be changed according to the value past to lambda's environment variable
   TableName: tableName
}
dynamodb.getItem(getItemParams, (err, result) => {
// some logic
}

Hence my question, is there any way to avoid hardcoding the table name in the batchGetItem method and, instead, allocate it dynamically like in the getItem method?

1 Answer 1

9

You can use the tableName from environment variables. Build your params in 2 steps :

const { tableName } = process.env;

const params = {
  RequestItems: {},
};

// `tableName` is your environment variable, it may have any value
params.RequestItems[tableName] = {
  Keys: [], //array of keys
};

dynamodb.batchGetItem(params, (err, result) => {
  // some logic
})
Sign up to request clarification or add additional context in comments.

2 Comments

hey @costin , can you suggest me best tutorial for aws lambda
@pyd There is no best tutorial, the best is the one that helps you advance. Read the docs and practice, this is the only way you can progress. • AWS Lambda Resources, • API Reference, etc. • Read blogs and questions, and, most important, fully understand what the options are in the AWS Lambda console. Good luck!

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.