1

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.

Community
  • 1
  • 1
prashant
  • 2,181
  • 2
  • 22
  • 37

1 Answers1

3

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>});
})
solosodium
  • 723
  • 5
  • 15
  • 1
    This is working well. It addition to that I had to add context.callbackWaitsForEmptyEventLoop = false; as first statement – prashant Jan 20 '17 at 22:44