Vik
Vik

Reputation: 9289

accessing realtime DB from firebase functions

We are using firebase functions and firebase real time DB for our mobile app. We do send emails when someone place an order which is implemented using firebase DB triggers like below:

exports.on_order_received = functions.database.ref("/orders/{id}")
    .onCreate((change, context) => {
        console.log("start of on_order_received")   
...

Above trigger works just fine for us. Now, we have some requirement where we do not have a DB trigger in the picture. It's a http request like below

exports.daily_sales_report = functions.https.onRequest((req, res) => {
    //query data from firebase

The question is how do we access the real time db objects here? or in other words how do i get the access to the /orders node ? I tried like below

exports.daily_sales_report = functions.https.onRequest((req, res) => {
    //query data from firebase
    var ref = functions.database.ref('orders')
    ref.orderByValue().limitToLast(3).on("value", function(snapshot) {
        snapshot.forEach(function(data) {
          console.log("The " + data.key + " dinosaur's score is " + data.val());
        });
    })

but this does not work. I get error "orderByValue() is not a function"

Upvotes: 7

Views: 12926

Answers (2)

Neelavar
Neelavar

Reputation: 368

You'll have to use the admin and not the functions to access the database() to read the data.

(Please ensure you've access to firebase-admin sdk, use import or require as appropriate depending on whether you are using TypeScript or JavaScript)

// The Firebase Admin SDK to access the Firebase Realtime Database.    
import * as admin from 'firebase-admin';

or

// The Firebase Admin SDK to access the Firebase Realtime Database.
const admin = require('firebase-admin');

Try this:

exports.daily_sales_report = functions.https.onRequest((req, res) => {
    //query data from firebase
    /* Do not use functions */ 
    // var ref = functions.database.ref('orders')
    /* Instead use the admin */
    var ref = admin.database().ref('orders')
    ref.orderByValue().limitToLast(3).on("value", function(snapshot) {
        snapshot.forEach(function(data) {
          console.log("The " + data.key + " dinosaur's score is " + data.val());
        });
    })

orderByValue() is not defined in functions.database - but is actually available in admin.database().ref()

Upvotes: 7

Doug Stevenson
Doug Stevenson

Reputation: 317322

You should use the Firebase Admin SDK. It has the ability to read and write your database. In fact, when you write a database trigger, the refs it gives you to work with actually come from the Admin SDK, so it's the same API. You just need to initialize it yourself when using HTTP type functions:

// at the top of the file:
const admin = require('firebase-admin');
admin.initializeApp();

// in your function:
const root = admin.database().ref();
// root is now a Reference to the root of your database.

Upvotes: 14

Related Questions