DynamoDB更新不console.log任何输出 [英] DynamoDB update does not console.log any output

查看:89
本文介绍了DynamoDB更新不console.log任何输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码。该代码应该接收SQS消息,读取正文,然后使用该正文中包含的信息更新发电机记录。该更新无法正常工作,这是一个问题,但即使是陌生人,我也无法从dynamodb更新中获得任何输出。输出的最后一行是console.log,其中详细说明了SQS消息,然后函数结束了。

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. The update is not working which is one issue, but even stranger I'm not getting any output from the dynamodb update. The last line of output is the console.log which details the SQS message, then the function ends.

这怎么可能?发电机不应该返回某种输出吗?

How is this possible? Shouldn't dynamo return some kind of 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...

// 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:我的两分钱,在您使用node.js运行时进行任何类型的Lamba开发之前,您应该了解javascript中回调,承诺,等待/异步之间的区别。

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.

这篇关于DynamoDB更新不console.log任何输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆