AWS -Lambda Я получаю сообщение об ошибке «MissingRequiredParameter: отсутствует параметр« Данные »в параметрах», но не вызывается параметр «Данные» - PullRequest
0 голосов
/ 03 апреля 2020

Я пытаюсь использовать AWS -Lambda для публикации данных через AWS -api шлюз на веб-странице на стороне клиента, но я застрял в сообщении об ошибке выше. При запуске функция запуска базы данных отображается, но затем застревает в сообщении об ошибке. Три набора кода, вставленные ниже, - вот что я использую. Если вы можете помочь, дайте мне знать также, если вам нужна дополнительная информация, дайте мне знать


database.js[
let AWS = require("aws-sdk");

//Create new DocumentClient
let docClient = new AWS.DynamoDB.DocumentClient();

//Returns all of the connection IDs
module.exports.getConnectionIds = async() => {
    let params = {
        TableName: "WebSocketClients"
    };
    return docClient.scan(params).promise();
};


module.exports.getCNYData = async() => {
    let params = {
        TableName: "Currency",
        Limit: 100,
        ScanIndexForward: true,
        IndexName: "Currency_Name-Date-index",
        KeyConditionExpression: "Currency_Name = :Currency",

        ExpressionAttributeValues: {
            ":Currency": "CNY",
        }

    };
    return docClient.query(params).promise();
};

module.exports.getGBXData = async() => {
    let params = {
        TableName: "Currency",
        Limit: 100,
        ScanIndexForward: false,
        IndexName: "Currency_Name-Date-index",
        KeyConditionExpression: "Currency_Name = :Currency",
        ExpressionAttributeValues: {
            ":Currency": "GBX",
        }
    };
    return docClient.query(params).promise();
};

module.exports.getSARData = async() => {
    let params = {
        TableName: "Currency",
        Limit: 100,
        ScanIndexForward: false,
        IndexName: "Currency_Name-Date-index",
        KeyConditionExpression: "Currency_Name = :Currency",
        ExpressionAttributeValues: {
            ":Currency": "SAR",
        }
    };
    return docClient.query(params).promise();
};

module.exports.getUSDData = async() => {
    let params = {
        TableName: "Currency",
        Limit: 100,
        ScanIndexForward: false,
        IndexName: "Currency_Name-Date-index",
        KeyConditionExpression: "Currency_Name = :Currency",
        ExpressionAttributeValues: {
            ":Currency": "USD",
        }
    };
    return docClient.query(params).promise();
};

module.exports.getPositiveSentimentData = async() => {
    let params = {
        TableName: "Sentiment",
        Limit: 100,
        ScanIndexForward: false,
        IndexName: "Sentiment-Id-index",
        KeyConditionExpression: "Sentiment = :sentiment",
        ExpressionAttributeValues: {
            ":sentiment": "POSITIVE",
        }
    };
    return docClient.query(params).promise();
};

module.exports.getNegativeSentimentData = async() => {
    let params = {
        TableName: "Sentiment",
        Limit: 100,
        ScanIndexForward: false,
        IndexName: "Sentiment-Id-index",
        KeyConditionExpression: "Sentiment = :sentiment",
        ExpressionAttributeValues: {
                    ":sentiment": "NEGATIVE",
        }
    };
    return docClient.query(params).promise();
};

module.exports.getData = async() => {
    let pSentiment = await module.exports.getPositiveSentimentData();
    let nSentiment = await module.exports.getNegativeSentimentData();
    let SAR = await module.exports.getSARData();
    let CNY = await module.exports.getCNYData();
    let USD = await module.exports.getUSDData();
    let GBX = await module.exports.getGBXData();
    let data = {
        positive: pSentiment,
        negative: nSentiment,
        CNY: CNY,
        GBX: GBX,
        SAR: SAR,
        USD: USD,
    };
    return data;
};

//Deletes the specified connection ID
module.exports.deleteConnectionId = async(connectionId) => {
    console.log("Deleting connection Id: " + connectionId);

    let params = {
        TableName: "WebSocketClients",
        Key: {
            ConnectionId: connectionId
        }
    };
    return docClient.delete(params).promise();
};
]

websocket.js[
let AWS = require("aws-sdk");

// Add ApiGatewayManagementApi to the AWS namespace
require('aws-sdk/clients/apigatewaymanagementapi');

//Import functions for database
let db = require('database');

module.exports.getSendMessagePromises = async(message, domainName, stage) => {
    //Get connection IDs of clients 
    let clientIdArray = (await db.getConnectionIds()).Items;
    console.log("\nClient IDs:\n" + JSON.stringify(clientIdArray));

    //Create API Gateway management class.
    const apigwManagementApi = new AWS.ApiGatewayManagementApi({
        apiVersion: '2018-11-29',
        endpoint: domainName + '/' + stage
    });

    //Try to send message to connected clients
    let msgPromiseArray = clientIdArray.map(async item => {
        try {

            console.log("Sending message '" + message + "' to: " + item.ConnectionId);



            //Create parameters for API Gateway

            let apiMsg = {

                ConnectionId: item.ConnectionId,

                Data: JSON.stringify(await db.getData)

            };



            //Wait for API Gateway to execute and log result

            await apigwManagementApi.postToConnection(apiMsg).promise();

            console.log("Message '" + message + "' sent to: " + item.ConnectionId);

        }

        catch (err) {

            console.log("Failed to send message to: " + item.ConnectionId);



            //Delete connection ID from database

            if (err.statusCode == 410) {

                try {

                    await db.deleteConnectionId(item.ConnectionId);

                }

                catch (err) {

                    console.log("ERROR deleting connectionId: " + JSON.stringify(err));

                    throw err;

                }

            }

            else {

                console.log("UNKNOWN ERROR: " + JSON.stringify(err));

                throw err;

            }

        }

    });
    return msgPromiseArray;
};

]


index.js[
//Import external library with websocket functions
let ws = require("websocket");
let db = require("database");

//Hard coded domain name and stage - use when pushing messages from server to client
let domainName = "*********";
let stage = "dev";

exports.handler = async (event) => {
    try {
        //Get Message from event
        const msg = JSON.stringify(await db.getData(), function(key, value){
            if (typeof value === "bigint") {
                return value.toString();
            } else {
                return value;
            }
        });


        //Allocate domain name and stage dynamically
        //domainName = event.requestContext.domainName;
        //stage = event.requestContext.stage;
        console.log("Domain: " + domainName + " stage: " + stage);

        //Get promises message to connected clients
        let sendMsgPromises = await ws.getSendMessagePromises(msg, domainName, stage); 

        //Execute promises
        await Promise.all(sendMsgPromises);
    }
    catch(err){
        return { statusCode: 500, body: "Error: " + (err)};
    }

    //Success
    return { statusCode: 200, body: "Data sent successfully." };
};
]

Редактировать: Для двух таблиц Dynamodb: Имя: Валюта Основной ключ раздела: Дата (строка), Основной ключ сортировки: имя_валюты (Строка), Поле: Цена (BigInt), Индекс: Currency_Name-Date-index.

Вторая таблица: Имя: Первичный ключ раздела настроения: Id (Number), Первичный ключ сортировки: Text (String), Поле : Sentiment (строка), индекс: Sentiment-Id-index.

Сообщение об ошибке:

Response:
{
  "statusCode": 500,
  "body": "Error: MissingRequiredParameter: Missing required key 'Data' in params"
}

Request ID:
"e2fee9cd-4af1-489e-8aac-98e16139dd4d"

Function Logs:
019-10-23"},{"Currency_Name":"USD","Price":"48.50","Date":"2019-10-22"},{"Currency_Name":"USD","Price":"47.32","Date":"2019-10-21"},{"Currency_Name":"USD","Price":"47.48","Date":"2019-10-18"},{"Currency_Name":"USD","Price":"48.69","Date":"2019-10-17"},{"Currency_Name":"USD","Price":"48.25","Date":"2019-10-16"},{"Currency_Name":"USD","Price":"47.00","Date":"2019-10-15"},{"Currency_Name":"USD","Price":"46.49","Date":"2019-10-14"},{"Currency_Name":"USD","Price":"46.10","Date":"2019-10-11"},{"Currency_Name":"USD","Price":"43.81","Date":"2019-10-10"},{"Currency_Name":"USD","Price":"43.65","Date":"2019-10-09"},{"Currency_Name":"USD","Price":"44.10","Date":"2019-10-08"},{"Currency_Name":"USD","Price":"45.66","Date":"2019-10-07"},{"Currency_Name":"USD","Price":"44.91","Date":"2019-10-04"},{"Currency_Name":"USD","Price":"42.70","Date":"2019-10-03"},{"Currency_Name":"USD","Price":"43.50","Date":"2019-10-02"},{"Currency_Name":"USD","Price":"45.50","Date":"2019-10-01"},{"Currency_Name":"USD","Price":"44.62","Date":"2019-09-30"},{"Currency_Name":"USD","Price":"45.67","Date":"2019-09-27"},{"Currency_Name":"USD","Price":"46.22","Date":"2019-09-26"},{"Currency_Name":"USD","Price":"44.42","Date":"2019-09-25"},{"Currency_Name":"USD","Price":"47.33","Date":"2019-09-24"},{"Currency_Name":"USD","Price":"45.83","Date":"2019-09-23"},{"Currency_Name":"USD","Price":"47.89","Date":"2019-09-20"},{"Currency_Name":"USD","Price":"48.23","Date":"2019-09-19"},{"Currency_Name":"USD","Price":"48.04","Date":"2019-09-18"},{"Currency_Name":"USD","Price":"47.77","Date":"2019-09-17"},{"Currency_Name":"USD","Price":"47.53","Date":"2019-09-16"},{"Currency_Name":"USD","Price":"49.21","Date":"2019-09-13"},{"Currency_Name":"USD","Price":"49.50","Date":"2019-09-12"},{"Currency_Name":"USD","Price":"47.74","Date":"2019-09-11"},{"Currency_Name":"USD","Price":"46.75","Date":"2019-09-10"},{"Currency_Name":"USD","Price":"47.19","Date":"2019-09-09"},{"Currency_Name":"USD","Price":"46.65","Date":"2019-09-06"},{"Currency_Name":"USD","Price":"45.39","Date":"2019-09-05"},{"Currency_Name":"USD","Price":"42.48","Date":"2019-09-04"},{"Currency_Name":"USD","Price":"41.79","Date":"2019-09-03"},{"Currency_Name":"USD","Price":"42.87","Date":"2019-08-30"},{"Currency_Name":"USD","Price":"41.63","Date":"2019-08-29"},{"Currency_Name":"USD","Price":"39.61","Date":"2019-08-28"},{"Currency_Name":"USD","Price":"40.72","Date":"2019-08-27"},{"Currency_Name":"USD","Price":"40.47","Date":"2019-08-26"},{"Currency_Name":"USD","Price":"42.07","Date":"2019-08-23"},{"Currency_Name":"USD","Price":"43.45","Date":"2019-08-22"},{"Currency_Name":"USD","Price":"43.25","Date":"2019-08-21"},{"Currency_Name":"USD","Price":"42.95","Date":"2019-08-20"},{"Currency_Name":"USD","Price":"43.53","Date":"2019-08-19"},{"Currency_Name":"USD","Price":"40.19","Date":"2019-08-16"},{"Currency_Name":"USD","Price":"39.77","Date":"2019-08-15"},{"Currency_Name":"USD","Price":"40.90","Date":"2019-08-14"},{"Currency_Name":"USD","Price":"39.55","Date":"2019-08-13"},{"Currency_Name":"USD","Price":"39.85","Date":"2019-08-12"},{"Currency_Name":"USD","Price":"41.25","Date":"2019-08-09"}],"Count":100,"ScannedCount":100,"LastEvaluatedKey":{"Currency_Name":"USD","Date":"2019-08-09"}}}' to: KYSQycomoAMCJdA=
2020-04-03T14:09:16.092Z    e2fee9cd-4af1-489e-8aac-98e16139dd4d    INFO    Sending message '{"positive":{"Items":[{"Sentiment":"POSITIVE","Id":"1238393433607131100n","Text":"\"Nice, didn’t get boated ? *********""}],"Count":1,"ScannedCount":1},"negative":{"Items":[{"Sentiment":"NEGATIVE","Id":"1238395098741825500n","Text":"\"RT @keira_churchill: GBP plummets against the Euro because coronavirus. GBP plummets against the USD because coronavirus. GBP plummets agai…\""},{"Sentiment":"NEGATIVE","Id":"1238392914813816800n","Text":"\"@keira_churchill GBP was already weakened by Brexit uncertainty/risks. Add CoronavEND RequestId: e2fee9cd-4af1-489e-8aac-98e16139dd4d

1 Ответ

0 голосов
/ 26 апреля 2020

postToConnection требует атрибут данных. В вашем случае это будет неопределенным, поскольку JSON .stringify вернет неопределенное при попытке строкового преобразования функции. Это происходит потому, что вы забыли скобки при вызове функции getData.

Заменить:

let apiMsg = {
  ConnectionId: item.ConnectionId,
  Data: JSON.stringify(await db.getData) // This results in undefined.
};

С:

let apiMsg = {
  ConnectionId: item.ConnectionId,
  Data: JSON.stringify(await db.getData()) // This works like you are expecting.
};
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...