0
votes

I'm setting up an API to scan a table on DynamoDB using Async function with Node.js 8.10. When I call the scan method I use the the AWS SDK 2.3 Promise to ensure that the query is performed. However, I want to return a custom JSON having info of the status code and on the body the data received from the database.

I'm using a separate async function for the promise. This function receives user input that's provided from the exports.handler function. I create the params array with the info for the query and finally call the scan function to perform the query on the table as a promise. Lastly, within the promise I create a new variable with the info I want to return, but even if I return the var it'll always return the promise.


const paramQuery = async () => {
    return await  paramQuery();
}

const paramQuery = async () => {
    let params = {
        TableName: process.env.TABLE_NAME;
    };

    var queryParams = documentClient.scan(params).promise();
    queryParams.then(function(data) {
        let response = {
            "statusCode": 200,
            "body": (data.Items)
        }
        return response;
    }).catch(function(err){
        console.log(err);
    });
    return queryParams;
}


// Expected result:

Response:
{
  "statusCode": 200,
  "body": [{
    "ParameterName": "Name",
    "ParameterValue": "Value"
  }, {
    "ParameterName": "Name",
    "ParameterValue": "Value"
  }]
}

// Current result:

Response:
{
  "Items": [
    {
     "ParameterName": "Name",
     "ParameterValue": "Value"
    },
    {
     "ParameterName": "Name",
     "ParameterValue": "Value"
    }
  ],
  "Count": 2,
  "ScannedCount": 2
}

I've tried looking for similar questions, but haven't found any that relates exactly to my problem. Ideally, explicit calls to resolve or reject should be avoided.

1

1 Answers

0
votes

Try this.

const paramQuery = async () => {
    return await  paramQuery();
}

const paramQuery = async () => {
    let params = {
        TableName: process.env.TABLE_NAME;
    };
return new Promise((resolve, reject) => {
    var queryParams = documentClient.scan(params).promise();
    queryParams.then(function(data) {
      resolve({
            "statusCode": 200,
            "body": (data.Items)
        });
    }).catch(function(err){
       reject(err)
    });
});
}