简体   繁体   中英

AWS Lambda function timing out while adding firebase entry

I am having trouble saving data in firebase database using lambda function. It times out. I have tried to set a timeout till 5 minutes,which ideally it should not take to execute but still its timing out.

'use strict';

var firebase = require('firebase');

exports.handler = (event, context, callback) => {

    console.log(context);

    var params = JSON.stringify(event);

    var config = {
    apiKey: "SECRETAPIKEY",
    authDomain: "myapplication.firebaseapp.com",
    databaseURL: "https://myapplication.firebaseio.com",
    storageBucket: "myapplication.appspot.com",
    messagingSenderId: "102938102938123"
    };

    if(firebase.apps.length === 0) {   // <---Important!!! In lambda, it will cause double initialization.
        firebase.initializeApp(config);
    }

    var db = firebase.database();

    var postData = {
    username: "test",
    email: "test@mail.com"
    };

    // Get a key for a new Post.
    var newPostKey = firebase.database().ref().child('posts').push().key;

    // Write the new post's data simultaneously in the posts list and the user's post list.
    var updates = {};
    updates['/posts/' + newPostKey] = postData;

    callback(null, {"Hello": firebase.database().ref().update(updates)}); // SUCCESS with message
};

Above code saves data in firebase but it times out.

If I use context.callbackWaitsForEmptyEventLoop = false as explained in Link it does not time out but data is not getting saved.

Please let me know how I can fix this issue. There are is no useful information in cloudwatch.

One more thing, If I use rest api for firebase to save the data it works well.

The problem is that your callback function

callback(null, {"Hello": firebase.database().ref().update(updates)}); // SUCCESS with message

is invoked before Firebase can make the update.

Instead of your current callback, you should put your callback function in Firebase update callback:

firebase.database().ref().update(updates, function (err) {

    // your processing code here

    callback(null, {<data to send back>});
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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