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: "[email protected]"
    };

    // 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.

1

1 Answer 1

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>});
})
Sign up to request clarification or add additional context in comments.

1 Comment

This is working well. It addition to that I had to add context.callbackWaitsForEmptyEventLoop = false; as first statement

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.