简体   繁体   English

DynamoDB 更新不会 console.log 任何 output

[英]DynamoDB update does not console.log any output

I have the following code.我有以下代码。 This code is supposed to receive an SQS message, read the body, then update a dynamo record with the information contained within that body.此代码应该接收 SQS 消息,读取正文,然后使用该正文中包含的信息更新 dynamo 记录。 The update is not working which is one issue, but even stranger I'm not getting any output from the dynamodb update.更新不起作用,这是一个问题,但更奇怪的是,我没有从 dynamodb 更新中得到任何 output。 The last line of output is the console.log which details the SQS message, then the function ends. output 的最后一行是详细说明 SQS 消息的 console.log,然后 function 结束。

How is this possible?这怎么可能? Shouldn't dynamo return some kind of output?发电机不应该返回某种 output 吗?

console.log('Loading function');
const util = require('util')
const AWS = require('aws-sdk');
var documentClient = new AWS.DynamoDB.DocumentClient();


exports.handler = async(event) => {
    //console.log('Received event:', JSON.stringify(event, null, 2));
    for (const { messageId, body } of event.Records) {
        //const { body } = event.Records[0];
        //console.log(body)
        console.log('SQS message %s: %j', messageId, body);
        const JSONBody = JSON.parse(body)
        //const message = JSON.parse(test["Message"]);
        const id = JSONBody.id;
        const city = JSONBody.City;
        const address = JSONBody.Address;

        const params = {
            TableName: 'myTable',
            Key: {
                ID: ':id',
            },
            UpdateExpression: 'set address = :address',
            ExpressionAttributeValues: {
                ':id': id,
                ':address': address,
                ':sortKey': "null"
            }
            //ReturnValues: "UPDATED_NEW"
        };

        documentClient.update(params, function(err, data) {
            if (err) console.log(err);
            else console.log(data);
        });
    }
    return `Successfully processed ${event.Records.length} messages.`;
};

There're a couple of ways to do this, but I'm sure about your use cases: Are operations are critical?有几种方法可以做到这一点,但我确信您的用例:操作是否至关重要? Do the failed items need to be handled?是否需要处理失败的项目? Are performance need to be boosted as the large dataset?作为大型数据集,是否需要提高性能? etc... ETC...

// I'm not recommend to this implementation
const { DynamoDB } = require('aws-sdk');
const documentClient = new DynamoDB.DocumentClient();


exports.handler = async (event) => {
    for (const { messageId, body } of event.Records) {
        console.log('SQS message %s: %j', messageId, body);
        // Parse json is dangerous without knowing the structure, remember to handle
        // when error occured
        const JSONBody = JSON.parse(body)
        const id = JSONBody.id;
        const address = JSONBody.Address;

        const params = {
            TableName: 'myTable',
            Key: {
                ID: ':id',
            },
            UpdateExpression: 'set address = :address',
            ExpressionAttributeValues: {
                ':id': id,
                ':address': address,
                ':sortKey': "null"
            },
            ReturnValues: "UPDATED_NEW"
        };

        // Wait for each update operation to finished
        // IO time will be extended
        await documentClient.update(params)
            .promise()
            .then(res => {
                console.log(res)
            })
            .catch(err => {
                console.error(err);
            })
    }

    // In case there's a failed update operation, this message still be returned by lambda handler
    return `Successfully processed ${event.Records.length} messages.`;
};
// My recommended way
const AWS = require('aws-sdk');
const documentClient = new AWS.DynamoDB.DocumentClient();


exports.handler = async (event) => {
    // All the update operation is fired nearly concurrently
    // IO will be reduced
    return Promise.all(event.Records.map(({ messageId, body }) => {
        console.log('SQS message %s: %j', messageId, body);
        // Parse json is dangerous without knowing the structure, remember to handle
        // when error occured
        const JSONBody = JSON.parse(body)
        const id = JSONBody.id;
        const address = JSONBody.Address;

        const params = {
            TableName: 'myTable',
            Key: {
                ID: ':id',
            },
            UpdateExpression: 'set address = :address',
            ExpressionAttributeValues: {
                ':id': id,
                ':address': address,
                ':sortKey': "null"
            },
            ReturnValues: "UPDATED_NEW"
        };

        return documentClient.update(params)
            .promise()
            .then(res => {
                console.log(res)
            })
    }))
        // When lambda handler finised all the update, lambda handler return a string
        .then(() => {
            return `Successfully processed ${event.Records.length} messages.`
        })
        // In case any of the update operation failed, the next update operations is cancelled
        // Lambda handler return undefined
        .catch(error => {
            console.error(error);
            // return some error for lambda response.
        })
};

P/s: My two cents, before you do any kind of Lamba development with node.js runtime, you should understand the differences between callbacks, promises, await/async in javascript. P/s:我的两分钱,在您使用 node.js 运行时进行任何类型的 Lamba 开发之前,您应该了解 javascript 中回调、承诺、等待/异步之间的区别。

Fixed it by making the method synchronous, ie removed async from the function def通过使方法同步来修复它,即从 function def 中删除异步

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM