Anyone know how to use multiple databases/projects with cloud functions?

332 views
Skip to first unread message

Tom Butler

unread,
Sep 1, 2017, 8:13:29 PM9/1/17
to Firebase Google Group
I have a project that needs a cloud function(s) to fire off when a change is made to a realtime database (database A) and write something to a separate realtime database in another project (same owner).  The initialization of  admin.initializeApp(functions.config().firebase); connects fine to its own database (database A), but I have no idea how to make a new reference serverside.  

I have multiple projects/databases connected using front end code using:

  // main app database
  var AppConfig = (function(){
    return (window.location.host.indexOf('gorout.com') === -1)
    // development
    ? {
      apiKey: "<APIKEY>",
      authDomain: "staging.firebaseapp.com",
      databaseURL: "https://url.firebaseio.com",
      projectId: "myproject"
    }
    // production
    : {
      apiKey: "<APIKEY>",
      authDomain: "production.firebaseapp.com",
      databaseURL: "https://ulr.firebaseio.com",
      projectId: "myproject"
    }
  }());
  
  var appDB = firebase.initializeApp(AppConfig, "appDB "); 
  
  // output database version  
  var getDatabaseVersion = appDB.database().ref('config/version');
  getDatabaseVersion.on('value', function(snapshot) {
    console.log(snapshot.val());
  });
  
  // =========================================================================
  // SECONDARY DATABASE (STATS-TEMP)
  // =========================================================================
  
  // get stats database
  var statsConfig = {
    apiKey: "<APIKEY>",
    authDomain: "stats.firebaseapp.com",
    databaseURL: "https://url.firebaseio.com",
  };
  
  var statsDB = firebase.initializeApp(statsConfig, "statsConfig");

// test queue transactions
  var queueEventRef = statsDB.database().ref().child('queue/tasks');
  queueEventRef.on('value', function(snapshot) {
    if(snapshot.val()) {
      snapshot.forEach(function(data) {
          var orgid = data.val().organizationId;
          var state = data.val()['_state'];
          console.log(orgid,state);
      });
    }
  });

That all works perfectly in my application code. But I have no idea how to replicate such a connection scenario within ./function/index.js.   have not been able to find any docs on that either.  I'm sure it's super simple if you know the approach, but I'm tired of banging my head. If anyone has any suggestions or code snippets, that would be great.  Thanks!!

Reply all
Reply to author
Forward
0 new messages