最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Nodejs AWS Lambda 函数不返回任何响应

网站源码admin39浏览0评论

Nodejs AWS Lambda 函数不返回任何响应

Nodejs AWS Lambda 函数不返回任何响应

我正在使用 nodejs 编写代码。我正在从 AWS SQS 中提取数据并将记录插入 Dynamodb。

我正在使用承诺链。它在本地运行良好。但是当我部署代码时,AWS lambda 没有返回任何响应。

代码也没有错误。不明白我做错了什么?

// Get the message from SQS and push to dynamodb

// Send Group Message to SQS
const AWS = require('aws-sdk');

const dynamodb = new AWS.DynamoDB.DocumentClient({
    region: "us-west-1",
});

const { v4: uuidv4 } = require('uuid');

const webSocketsTable = process.env.PROD_WEBSOCKETS;
const userNotificationInformation = process.env.PROD_USER_NOTIFICATION;

// Steps to follow first time when create any user request -

// Customized Notification Message
function customizedNotificationMessage(key) {
    switch(key) {
        case   0  :  
            return {
                header: 'Congratulations',
                body: 'New order submitted'
            };
        case   1  : 
            return {
                header: 'Alert',
                body: 'New order arrived'
            };
    }
}

// Step 1. Update the Customer Room Id
function get_customer_roomId(connectionId) {
    var params = {
        TableName: webSocketsTable,
        Key:{
            id: connectionId
        }
    }
    return new Promise((resolve, reject) => {
        dynamodb.get(params, function(err, data) {
            if (err) {
                reject(err);
            } else {
                resolve(data);
            }
        })
    })
}

// Step 2. Update room Id - Incoming room id push to the current user room -->
function update_user_roomId(id, userRooms, users) {
    var params = {
        TableName: webSocketsTable,
        Key:{
            id: id
        },
        UpdateExpression: 'set rooms = :val',
        ExpressionAttributeValues: {
            ':val': userRooms,
        }
    }
    return new Promise((resolve, reject) => {
        dynamodb.update(params, function(err, data) {
            if (err) {
                reject(err);
            } else {
                resolve({
                    message: "Successfully updated records.",
                    users: users
                });
            }
        })
    })
}

// Step 3. Push to the Notification Table
function pushTo_NotificationTable(user, id, roomId, message, flag) {
    var params = {
        TableName: userNotificationInformation,
        Item: {
            userid: flag == true ? user.id : user.userid,
            id: id,
            name: flag == true ? user.name : user.username,
            jobId: roomId,
            profileUrl: user.profileUrl,
            messageHeader: message.header,
            messageBody: message.body,
            createdAt: Date.now(),
        }
    };

    return new Promise((resolve, reject) => {
        dynamodb.put(params, function (err, data) {
            if (err) {
                reject(err);
            } else {
                resolve({
                  data: data,
                  success: true, 
                  message: "Successfully inserted notification records !!! "
                })
            }
        })
    })
}

// Step 4 - Get Assigned Business Analysts Rooms
function get_business_analysts_roomId(email) {
    var params = {
        TableName: webSocketsTable,
        FilterExpression: 'useremail = :val',
        ExpressionAttributeValues: {
            ':val': email,
        }
    }
    return dynamodb.scan(params).promise();
}

exports.handler = async(event, context, callback) => {
    try {
        const records = event.Records;
        for(let i = 0; i < records.length; i++) {
            var recordBody = JSON.parse(records[i].body);
            var id = recordBody.id;
            var uniqueId = uuidv4();
            var roomId = recordBody.roomId;
            var customerData = recordBody.customerData;
            var businessAnalystsData = recordBody.businessAnalystsData;
            var businessAnalystsEmailId = businessAnalystsData.email;
           
            get_customer_roomId(id).then((getCustomerRooms) => {
                const data = JSON.parse(JSON.stringify(getCustomerRooms.Item));
                const userRooms = [...data.rooms];
                userRooms.push(roomId);
                return update_user_roomId(id, userRooms, data);
            }).then((updateUsersToRooms) => {
                
                console.log("Step 2: Customer successfully connected to a room.");
                updateUsersToRooms.users.profileUrl = customerData.profileUrl;
                // Push notication integration here, insert customer record
                const pushNotication = customizedNotificationMessage(0);
                return pushTo_NotificationTable(updateUsersToRooms.users, uniqueId, roomId, pushNotication, false);
            }).then((pushNotication) => {
                console.log("Step 3: Push notification updated for the customer.");
                return get_business_analysts_roomId(businessAnalystsEmailId);
            }).then(async(res) => {
                const data = JSON.parse(JSON.stringify(res.Items));
                if(data.length == 0) { // No business analysts online push to notification table
                    console.log("Step 4: Business Analysts are not online."); 
                    
                    // Push to Notification Table   
                    const pushNotication = customizedNotificationMessage(1);
                    const pushNoticationUpdate = await pushTo_NotificationTable(businessAnalystsData, uniqueId, roomId, pushNotication, true);
                    console.log("Step 5: Push notification updated for the business analysts.");
                    context.done(null, event);
                } else {
                    console.log("Step 4: Business Analysts are online.")
                    const businessAnalysts = data.pop();
                    const userRooms = [...businessAnalysts.rooms];
                    userRooms.push(roomId);
                    const updateRoom = await update_user_roomId(businessAnalysts.id, userRooms, businessAnalysts);
                    console.log("Step 5: Customer and business analysts are successfully connected via rooms.");
                    
                    // Push to Notification Table   
                    const pushNotication = customizedNotificationMessage(1);
                    const pushNoticationUpdate = await pushTo_NotificationTable(businessAnalysts, uniqueId, roomId, pushNotication, false);
                    console.log("Step 6: Push notification updated for the business analysts.");
                    context.done(null, event);
                }
                

            }).catch((errMessage) => {
                console.log("Error message:", errMessage)
                context.fail(errMessage, null);
            })   
        }
    } catch(err) {
        console.log("Error:", err);
        context.fail(err, null);
    }
}

任何帮助将不胜感激。

回答如下:

我无法为一个简单的建议添加评论,因为我没有 50 声望

无论如何,试试

context.callbackWaitsForEmptyEventLoop = false;
https://docs.aws.amazon/lambda/latest/dg/nodejs-context.html

发布评论

评论列表(0)

  1. 暂无评论