2

我想在我的Firebase應用程序上調用雲功能後,在我的數據庫上執行查詢。如何從雲端函數內部運行查詢?

比方說,我對數據庫有一定的觸發器,請考慮get started guide on Firebase中提供的示例。

// Listens for new messages added to /messages/:pushId/original and creates an 
// uppercase version of the message to /messages/:pushId/uppercase 
exports.makeUppercase = functions.database.ref('/messages/{pushId}/original') 
    .onWrite(event => { 
     // Grab the current value of what was written to the Realtime Database. 
     const original = event.data.val(); 
     console.log('Uppercasing', event.params.pushId, original); 
     const uppercase = original.toUpperCase(); 
     // I'D LIKE TO PERFORM A QUERY HERE, JUST A SIMPLE RETRIEVE BASED ON THE ID PROVIDED 
    // You must return a Promise when performing asynchronous tasks inside a Functions such as 
    // writing to the Firebase Realtime Database. 
    // Setting an "uppercase" sibling in the Realtime Database returns a Promise. 
    return event.data.ref.parent.child('uppercase').set(uppercase); 
}); 

哪些模塊我應該進口,如果有的話? 如何在數據庫上執行查詢?

預先感謝您的回答!

回答

9

您可以使用此Node.js Admin SDK

const functions = require('firebase-functions'); 
const admin = require('firebase-admin'); 
admin.initializeApp(functions.config().firebase); 

exports.makeUppercase = functions.database 
    .ref('/messages/{pushId}/original') 
    .onWrite(event => { 
    return admin.database().ref('/other') 
     .orderByChild('id').equalTo(event.params.pushId) 
     .once('value').then(snapshot => { 
     // there, I queried! 
     }); 
    });