查询dynamo数据库的node.js函数始终返回未定义

时间:2020-06-22 12:37:24

标签: javascript node.js amazon-web-services asynchronous amazon-dynamodb

我具有以下函数定义。本质上,它要做的是查询DynamoDB表并返回相应分区键的deviceID。

GetDeviceIdFromHash: function (id) {
    const params = {
        TableName: process.env.USER_TABLE,
        Key: {
            id: id
        }
    };
    dynamoDb.get(params, function(error, result) {
        // handle potential errors
        if (error) {
            console.log(error);
            return "";
        }
        return result;
    });
}

问题在于,无论数据库中是否存在undefined属性,该函数总是返回id

我不确定为什么会这样。

基于我的直觉,我认为这可能与dynamoDb.get()是一个异步语句有关,但是我对node.js的经验有限,所以我不知道如何进行。

该函数的调用者:

'use strict';

const AWS = require('aws-sdk'); // eslint-disable-line import/no-extraneous-dependencies
const dynamoDb = new AWS.DynamoDB.DocumentClient();
const push = require('./helper.js')

module.exports.update = async (event, context, callback) => {
    const data = JSON.parse(event.body);
    // validation
    if (typeof data.userid !== 'string' || typeof data.restaurantid !== 'string' || typeof data.orderTime !== 'string' || typeof data.status !== 'string'
        || typeof data.confirmedtime !== 'string' || typeof data.expecteddeliverytime !== 'string' || typeof data.readytime !== 'string' || typeof data.contents !== 'string') {
        console.error('Validation Failed');
        callback(null, {
            statusCode: 400,
            headers: { 'Content-Type': 'text/plain' },
            body: 'Couldn\'t update the order',
        });
        return;
    }

    const params = {
        TableName: process.env.ORDER_TABLE,
        Key: {
            id: event.pathParameters.id,
        },
        ExpressionAttributeNames: {
            '#userid': 'userid',
            '#restaurantid': 'restaurantid',
            '#orderTime': 'orderTime',
            '#status': 'status',
            '#confirmedtime': 'confirmedtime',
            '#expecteddeliverytime': 'expecteddeliverytime',
            '#readytime': 'readytime',
            '#contents': 'contents',
        },
        ExpressionAttributeValues: {
            ':userid': data.userid,
            ':restaurantid': data.restaurantid,
            ':orderTime': data.orderTime,
            ':status': data.status,
            ':confirmedtime': data.confirmedtime,
            ':expecteddeliverytime': data.expecteddeliverytime,
            ':readytime': data.readytime,
            ':contents': data.contents
        },
        UpdateExpression: 'SET #userid = :userid, #restaurantid = :restaurantid, #orderTime = :orderTime, #status = :status, #confirmedtime = :confirmedtime, #expecteddeliverytime = :expecteddeliverytime, #readytime = :readytime, #contents = :contents',
        ReturnValues: 'ALL_NEW',
    };

    // update the address in the database
    dynamoDb.update(params, (error, result) => {
        // handle potential errors
        if (error) {
            console.error(error);
            callback(null, {
                statusCode: error.statusCode || 501,
                headers: { 'Content-Type': 'text/plain' },
                body: 'Couldn\'t update the order.'
            });
            return;
        }
        // send push notification of new order status
          var device_id = await push.GetDeviceIdFromHash(data.userid);
          var push_data = push.generatePushNotification("Order status update!", data.status);
          var res = push.sendPush(device_id, push_data);
          console.log(device_id);
          console.log(push_data);

        // create a response
        const response = {
            statusCode: 200,
            body: JSON.stringify(result.Attributes),
            headers: {
                'Access-Control-Allow-Origin': '*',
                'Access-Control-Allow-Credentials': true
            }
        };
        callback(null, response);
    });
};

1 个答案:

答案 0 :(得分:1)

是的,可能由于异步执行而发生。所以你可以尝试一下告诉我吗?

GetDeviceIdFromHash: async function (id) {
    const params = {
        TableName: process.env.USER_TABLE,
        Key: {
            id: id
        }
    };
    let result = await dynamoDb.get(params).promise();
    return result;
}

该函数的调用者:

'use strict';

const AWS = require('aws-sdk'); // eslint-disable-line import/no-extraneous-dependencies
const dynamoDb = new AWS.DynamoDB.DocumentClient();
const push = require('./helper.js')

module.exports.update = async (event, context, callback) => {
    const data = JSON.parse(event.body);
    // validation
    if (typeof data.userid !== 'string' || typeof data.restaurantid !== 'string' || typeof data.orderTime !== 'string' || typeof data.status !== 'string'
        || typeof data.confirmedtime !== 'string' || typeof data.expecteddeliverytime !== 'string' || typeof data.readytime !== 'string' || typeof data.contents !== 'string') {
        console.error('Validation Failed');
        callback(null, {
            statusCode: 400,
            headers: { 'Content-Type': 'text/plain' },
            body: 'Couldn\'t update the order',
        });
        return;
    }

    const params = {
        TableName: process.env.ORDER_TABLE,
        Key: {
            id: event.pathParameters.id,
        },
        ExpressionAttributeNames: {
            '#userid': 'userid',
            '#restaurantid': 'restaurantid',
            '#orderTime': 'orderTime',
            '#status': 'status',
            '#confirmedtime': 'confirmedtime',
            '#expecteddeliverytime': 'expecteddeliverytime',
            '#readytime': 'readytime',
            '#contents': 'contents',
        },
        ExpressionAttributeValues: {
            ':userid': data.userid,
            ':restaurantid': data.restaurantid,
            ':orderTime': data.orderTime,
            ':status': data.status,
            ':confirmedtime': data.confirmedtime,
            ':expecteddeliverytime': data.expecteddeliverytime,
            ':readytime': data.readytime,
            ':contents': data.contents
        },
        UpdateExpression: 'SET #userid = :userid, #restaurantid = :restaurantid, #orderTime = :orderTime, #status = :status, #confirmedtime = :confirmedtime, #expecteddeliverytime = :expecteddeliverytime, #readytime = :readytime, #contents = :contents',
        ReturnValues: 'ALL_NEW',
    };

    // update the address in the database
    dynamoDb.update(params, (error, result) => {
        // handle potential errors
        if (error) {
            console.error(error);
            callback(null, {
                statusCode: error.statusCode || 501,
                headers: { 'Content-Type': 'text/plain' },
                body: 'Couldn\'t update the order.'
            });
            return;
        }
        // send push notification of new order status
          var device_id = await push.GetDeviceIdFromHash(data.userid);
          var push_data = push.generatePushNotification("Order status update!", data.status);
          var res = push.sendPush(device_id, push_data);
          console.log(device_id);
          console.log(push_data);

        // create a response
        const response = {
            statusCode: 200,
            body: JSON.stringify(result.Attributes),
            headers: {
                'Access-Control-Allow-Origin': '*',
                'Access-Control-Allow-Credentials': true
            }
        };
        callback(null, response);
    });
};