Argiator Morimoto
Argiator Morimoto

Reputation: 156

Get Firebase Database Value into a Cloud Function

I'm currently using Firebase Functions to send automatic push notifications when the database is uploaded. It's working perfectly, I'm just wondering how I can get a specific value from my database, for example PostTitle and display it on, for example title.

In Firebase my database is /post/(postId)/PostTitle

const functions = require('firebase-functions');
const admin = require('firebase-admin');

admin.initializeApp(functions.config().firebase);
// database tree
exports.sendPushNotification = functions.database.ref('/posts/{id}').onWrite(event =>{
    const payload = {
        notification: {
           title: 'This is the title.',
            body: 'There is a new post available.',
            badge: '0',
            sound: 'default',
        }

    };
    return admin.database().ref('fcmToken').once('value').then(allToken => {
        if (allToken.val()){
            const token = Object.keys(allToken.val());
            console.log(`token? ${token}`);
            return admin.messaging().sendToDevice(token, payload).then(response =>{
              return null;
            });
        }

        return null;
    });
});

Upvotes: 0

Views: 1222

Answers (2)

Martin Zeitler
Martin Zeitler

Reputation: 76879

I'd use ...

var postTitle = event.data.child("PostTitle").val;

while possibly checking, it the title even has a value

... before sending out any notifications.

Upvotes: 0

Renaud Tarnec
Renaud Tarnec

Reputation: 83191

If I understand correctly that you want to get the PostTitle from the node that triggers the Cloud Function, the following should do the trick:

const functions = require('firebase-functions');
const admin = require('firebase-admin');

admin.initializeApp(functions.config().firebase);
// database tree
exports.sendPushNotification = functions.database.ref('/posts/{id}').onWrite(event =>{

    const afterData = event.data.val();  
    const postTitle = afterData.PostTitle;  //You get the value of PostTitle

    const payload = {
        notification: {
           title: postTitle,  //You then use this value in your payload
            body: 'There is a new post available.',
            badge: '0',
            sound: 'default',
        }

    };
    return admin.database().ref('fcmToken').once('value').then(allToken => {
        if (allToken.val()){
            const token = Object.keys(allToken.val());
            console.log(`token? ${token}`);
            return admin.messaging().sendToDevice(token, payload)
        } else {
            throw new Error('error message to adapt');
        }
    })
    .catch(err => {
      console.error('ERROR:', err);
      return false; 
    });
});

Note the following points:

  1. You are using the old syntax for Cloud Functions, i.e. the one of versions <= v0.9.1. You should migrate to the new version and syntax, as explained here: https://firebase.google.com/docs/functions/beta-v1-diff#realtime-database
  2. I have re-organised your promise chaining and also added a catch() at the end of the chain.

Upvotes: 1

Related Questions