How to access multiple Realtime Database instances in Cloud Functions for Firebase

后端 未结 4 1362
无人及你
无人及你 2020-12-16 19:49

I\'m using multiple databases in a Firebase project. Cloud functions for the main (default) database work great, however, I cannot make them work for a secondary database. F

4条回答
  •  独厮守ぢ
    2020-12-16 20:05

    With cloud functions > 1.1 now, here is the documentation link that saved my life on this issue.

    https://firebase.google.com/docs/database/usage/sharding#connect_your_app_to_multiple_database_instances

    So, it looks like this at the top of my my cloud function index.js :

    const functions = require('firebase-functions');
    const admin = require('firebase-admin');
    admin.initializeApp();
    
    const dev = admin.initializeApp({
      databaseURL: "https://appdev.firebaseio.com"
    }, 'dev');
    
    const v2 = admin.initializeApp({
      databaseURL: "https://appv2.firebaseio.com"
    }, 'v2');
    

    and then, in my clond functions functions code I can do :

    //will change stuff on default database
    admin.database().ref().child(`stuff/${stuffId}`).set(myStuff)
    
    //will change stuff on my dev database
    admin.database(dev).ref().child(`stuff/${stuffId}`).set(myStuff)
    
    //will change stuff on my v2 database
    admin.database(v2).ref().child(`stuff/${stuffId}`).set(myStuff)
    

提交回复
热议问题