How to query DynamoDB from a Dialogflow Fulfillment Webhook (JS)

This might be useful to someone so I will leave it here:

Sometimes in Dialogflow, we will want to query a NoSQL database like DynamoDB. The problem with simply querying without a promise is that the query is performed asynchronously, therefore the fulfillment won’t wait for the DynamoDB response and we will get an error if, for example, we want to use a value from the returned JSON in an agent.add(”something”) call. So to wait for the response, we could use something like this:


//Declaring the DynamoDB Object
let myDynamo = new aws.DynamoDB.DocumentClient({apiVersion: '2012-08-10'});

function myfunction(agent) {
      
			var parameters = 
      { 
      TableName:'SOMETABLE in DYNAMODB', 
      Key: {'PartitionKey': parseInt(id)} //If INT, Schema needs to match to dynamo Table
      };
      
      var promise_response = myDynamo.get(parameters).promise();

      return promise_response.then((response) => {

        console.log('success',JSON.stringify(response,null,2));
        agent.add(response.Item.value);
        }).catch((response) => {
        console.log('error',JSON.stringify(response,null,2));
        });

    }

return myfunction(agent);