Search code examples
node.jsfirebase-realtime-databasetwiliotwilio-functions

Twilio Function not writing to Firebase


I'm trying to write to my Firebase database using a Twilio function (almost exactly the same as AWS Lambda function, if you're familiar with that), but I'm unable to do so. Firebase is generating a reference key for me, but nothing appears in my Firebase database when I check it. I don't see any error message from my function. Here's what I'm working with.

var firebase = require('firebase');

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

  var firebaseConfigs = {
    apiKey: "[my_api_key]",
    authDomain: "[my_domain].firebaseapp.com",
    databaseURL: "https://[my_domain].firebaseio.com",
    projectId: "[my_project_id]",
    storageBucket: "[my_domain].appspot.com",
    messagingSenderId: "[my_sender_id]"
  };

  if (!firebase.apps.length) {
    firebase.initializeApp(firebaseConfigs);
    console.log('Initialized Firebase app');    
  }

  console.log('saving to firebase');

  var ref = firebase.database().ref().push({
    emailAddress: event.emailAddress,
    test: 'test'
  });

  console.log('saved to ',ref.key)

  setTimeout(function() {}, 3000);

  callback();
};

In my function logs, I see the following:

  • Execution Started
  • Initialized Firebase app
  • saving to firebase
  • saved to [-LdVpr...]
  • Execution ended in 974.16ms using 97 MB

Clearly Firebase is generating a key for me, but the key [-LdVpr...] is not added to my database. What could be happening, and how can I further troubleshoot this?


Solution

  • With Execution ended in 974.16ms in the logs, sounds like

    setTimeout(function() {}, 3000);
    callback(); 
    

    does not really do what you intended to do (wait for 3 seconds and then return to Twilio?).

    I would try this ...

    setTimeout(function() {
      callback();
    }, 3000);
    

    ... if that's what you'd like or need to do.


    Update after reading this https://firebase.google.com/docs/reference/js/firebase.database.Reference.html#push

    push() takes a second parameter, a "Callback called when write to server is complete.", so, I would also try something like this:

    var ref = firebase.database().ref().push({
      emailAddress: event.emailAddress,
      test: 'test'
    }, function (error) {
      if (error) {
        console.log(error);
        callback();
      } else {
        console.log('Push successful');
        callback();
      }
    
    });
    

    maybe you don't need that 3 seconds thing at all.