Including headers and data array in Return Statement with Node.js

白昼怎懂夜的黑 提交于 2020-12-15 01:48:32

问题


I have a lambda function that gets all items in a dynamoDB table as seen below. I am wondering if there is a way to include the response headers as well as the "scanResults" array in the return statement.

In my current code I can either include the headers or the scanResults array. I have tried putting two return statements but that is incorrect code. Is there a way to combine them? Thanks in advance for any help.

'use strict';
const AWS = require('aws-sdk');

exports.handler = async (event, context) => {
    const documentClient = new AWS.DynamoDB.DocumentClient();
    let responseBody = '';
    let statusCode = 0;
    let scanResults = [];
    let items;

    const params = {
        TableName: "Products"
    };

    do {
        items = await documentClient.scan(params).promise();
        items.Items.forEach((item) => scanResults.push(item));
        params.ExclusiveStartKey = items.LastEvaluatedKey;

        

    } while(typeof items.LastEvaluatedKey != "undefined");
        responseBody = JSON.stringify(items.Items);
        statusCode = 200;
        //return scanResults;


        const response = {
            statusCode: statusCode,
            headers: {
                "Content-Type": "application/json",
                "access-control-allow-origin": "*"
            },
            body: responseBody
        };
        return response;





};

回答1:


You are almost there, just missing an incorrect ref property of responseBody :

'use strict';
const AWS = require('aws-sdk');
const documentClient = new AWS.DynamoDB.DocumentClient();

exports.handler = async (event, context) => {
    let responseBody = '';
    let statusCode = 0;
    let scanResults = [];
    let items;

    const params = {
        TableName: "Products"
    };

    do {
      items = await documentClient.scan(params).promise();
      scanResults = [...scanResults, ...items.Items];
      params.ExclusiveStartKey = items.LastEvaluatedKey;
    } while(typeof items.LastEvaluatedKey != "undefined");
    responseBody = JSON.stringify(scanResults);
    statusCode = 200;
    const response = {
        statusCode: statusCode,
        headers: {
            "Content-Type": "application/json",
            "access-control-allow-origin": "*"
        },
        body: responseBody
    };
    return response;
};


来源:https://stackoverflow.com/questions/64868585/including-headers-and-data-array-in-return-statement-with-node-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!