Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DynamoDB BatchGetItem dynamic TableName in Lambda function

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?

like image 505
Wassily Avatar asked Oct 26 '25 10:10

Wassily


1 Answers

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
})
like image 156
Costin Avatar answered Oct 28 '25 23:10

Costin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!