Lambda nodeJS 4.3没有完成/执行成功回调

时间:2016-08-17 02:18:37

标签: firebase aws-lambda

尽管在其上方运行了日志语句,但我对callback(null)的调用无效。甚至尝试将它包装在try catch块中但什么都没有。

供参考,这是完整的功能:

var Firebase = require('firebase');
var request = require('request');

//noinspection AnonymousFunctionJS
/**
 *
 * @param event - from Lambda
 * @param context - from Lambda
 * @param callback - from Lambda
 */
exports.handler = function (event, context, callback) {
    var AUTOPILOT_API_KEY = getKey(event.stage, 'AUTOPILOT_API_KEY');
    var AUTOPILOT_JOURNEY_ID = getKey(event.stage, 'AUTOPILOT_JOURNEY_ID');
    activate();

    function activate () {
        console.log('event:', event);

        if (validPayload(event, context)) {
            addDefaultPresets(event.uid);
            addToAutopilot(event.user, event.uid);
        }
    }

    /**
     * checks that the necessary payload has been received
     * if YES: returns true and allows process to continue
     * if NO: throws context.fail with useful error message(s)
     * operating under custom error code naming convention of
     * http code + 3 digit ULM error code
     * @param event - from Lambda
     * @param context - from Lambda
     * @returns {boolean} - whether the payload contains the required data
     */
    function validPayload (event, context) {
        return true; // REDACTED FOR BREVITY
    }

    /**
     * Adds the user to Autopilot as a contact and adds them
     * to the journey with trigger id 0001
     * @param {Object} user
     * @param {string} uid generate by Firebase as unique identifier of registered user
     */
    function addToAutopilot (user, uid) {

        // REDACTED FOR BREVITY

        request({
            method: 'POST',
            url: 'https://api2.autopilothq.com/v1/trigger/' + AUTOPILOT_JOURNEY_ID + '/contact',
            headers: {
                'autopilotapikey': AUTOPILOT_API_KEY,
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(payload)
        }, function (error, response, body) {
            //noinspection MagicNumberJS
            if (response.statusCode !== 200) {
                errorResponse.status = response.statusCode;
                errorResponse.error = {
                    errorMessage: error,
                    user: event.user,
                    response: response,
                    body: body
                };
                console.log('should throw ERROR callback');
                context.fail(JSON.stringify(errorResponse));
            } else {
                console.log('should throw SUCCESS callback');
                console.log(JSON.stringify({
                    status: response.statusCode,
                    message: "User successfully added to Autopilot account & journey"
                }));

                callback(null);
            }
            console.log('Finished addToAutopilot()');
        });
    }

    /**
     * Adds a collection of presets the the account of the new user
     * @param uid {String} - Firebase UID
     */
    function addDefaultPresets (uid) {
        // REDACTED FOR BREVITY

        var presets = ref.child('users').child(uid).child('presets');

        console.log('Starting addDefaultPresets()');

        activate();

        function activate () {
            console.info('activating...');
            // for each field
            fields.forEach(function (field) {
                // iterate over each preset
                presetData[field].forEach(function (label) {
                    // and add to firebase db via addDefaultPreset() if unique
                    presetIsUnique(field, label);
                })
            });

            console.log('Finished addDefaultPresets()');
        }

        function presetIsUnique (field, label) {
            presets.child(field).orderByChild('label')
                .equalTo(label)
                .once('value', function (snapshot) {
                    var val = snapshot.val();
                    if (!val) {
                        addDefaultPreset(field, label);
                    } else {
                        console.error('already exists', field, label);
                    }
                });
        }

        function addDefaultPreset (field, label) {
            //noinspection MagicNumberJS
            presets.child(field).push().set({
                creator: 'default',
                dateAdded: Math.floor(Date.now() / 1000),
                label: label
            }, setCallback);
        }

        function setCallback (err) {
            if (err) {
                console.error(err);
            } else {
                console.info('added preset');
            }
        }
    }

    function getKey (stage, keyId) {
        var keys = {
            AUTOPILOT_API_KEY: {
                staging: 'dev123',
                prod: 'prod123'
            },
            AUTOPILOT_JOURNEY_ID: {
                staging: 'XXX',
                product: 'XXXX'
            },
            FIREBASE_URL: {
                staging: 'https://staging.firebaseio.com/',
                prod: 'https://prod.firebaseio.com/'
            }
        };

        if (stage === 'prod') {
            return keys[keyId][stage];
        } else {
            return keys[keyId]['staging'];
        }
    }
};

2 个答案:

答案 0 :(得分:3)

似乎firebase在事件循环中保留了一些东西。默认情况下,lambda在终止之前等待事件循环为空。您可以设置context.callbackWaitsForEmptyEventLoop = false以告诉lambda在调用回调后立即终止该函数,即使事件循环中仍有项目。

答案 1 :(得分:3)

经过几个小时的调试后,这对我有用:

var firebase = require('firebase');
var app = firebase.initializeApp(config);

...
...
...

app.delete().then(function(){
   var response = {
      statusCode: 200,
      body: JSON.stringify({
         message: 'Success'
      }),
   };
   callback(null, response);
});

您可以在official documentation中了解有关delete的更多信息:

  

使给定的应用程序无法使用并释放所有关联的资源   服务。

希望这有用!