将Firebase数据库的价值纳入云功能

时间:2018-08-09 16:31:16

标签: javascript firebase firebase-realtime-database firebase-cloud-messaging google-cloud-functions

我当前正在使用Firebase Functions在上载数据库时发送自动推送通知。它运行得很好,我只是想知道如何从数据库中获取特定值,例如PostTitle,并在其上显示它,例如title。

在Firebase中,我的数据库是/ 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;
    });
});

2 个答案:

答案 0 :(得分:0)

如果我正确理解您想从触发“云功能”的节点上获取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 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; 
    });
});

请注意以下几点:

  1. 您使用的是Cloud Functions的旧语法,即版本<= v0.9.1之一。您应该按照以下说明迁移到新版本和语法:https://firebase.google.com/docs/functions/beta-v1-diff#realtime-database
  2. 我重新组织了您的诺言链,并在链的末尾添加了catch()

答案 1 :(得分:0)

我会用...

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

在可能检查的同时,标题甚至具有值

...在发送任何通知之前。