Search code examples
node.jsaws-lambdaamazon-dynamodbaws-sdk-nodejs

Query() DynamoDB for each value in array on Lambda NodeJS


I have the following code in a NodeJS 12x Lambda function:

targetedAliases = ["abc", "efg"]; //Not used yet. But want to replace alias with this array.
alias = "abc" //using this one aka targetedAliases[0].

const dynamoDB = new AWS.DynamoDB({
    apiVersion: "2012-10-08"
});
var aliasScores;


const params = {
    TableName: 'a-table',
    FilterExpression: '#alias = :alias',
    ExpressionAttributeNames: {
        '#alias': 'alias',
    },
    ExpressionAttributeValues: {
        ':alias': {
            S: alias
        },
    }
};

aliasScores = await dynamoDB.scan(params).promise();

console.log("====> ", aliasScores);

The function as is prints the content of aliasScores as expected but I need to execute this n times for each item on the targetedAliases array.

Is there a way I can use a Array.forEach or something similar to execute a query/scan iteratively for each item in an array? Alternatively, can I use an array on the FilterExpression to execute the query/scan just once?

I want store each query/scan result in the aliasScores variable as a concatenation of all returned objects to use it further below.


Solution

  • You can use Promise.all with .map to execute these in parallel and get the results in array. Something like this

    const targetedAliases = ["abc", "efg"]; //Not used yet. But want to replace alias with this array.
    alias = "abc" //using this one aka targetedAliases[0].
    
    const dynamoDB = new AWS.DynamoDB({
        apiVersion: "2012-10-08"
    });
    var aliasScores;
    
    const result = await Promise.all(targetedAliases.map(alias => {
      const params = {
        TableName: 'a-table',
        FilterExpression: '#alias = :alias',
        ExpressionAttributeNames: {
            '#alias': 'alias',
        },
        ExpressionAttributeValues: {
            ':alias': {
                S: alias
            },
        }
    };
    
    return dynamoDB.scan(params).promise();
    }));
    
    console.log(result);