Firebase快照值从Cloud Function返回null

时间:2018-10-25 11:40:51

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

*图像删除

这是我的Firebase数据库,我正在尝试通过数据库中的更改或添加等事件来设置远程推送消息。

我已经进行了设置,以便多个设备可以共享同一帐户,并且每个设备作为子代写一个设备令牌,并将FCM令牌作为密钥存储在该子代下。

所以这里看到的关键值是[FCMtoken:true]

我正在弄乱Java语言的使用方式,这是我的函数返回空值,尽管我希望它返回设备FCMtoken。

exports.notificationForCommunicationAdded = functions.database.ref('/{pharmacyId}/orders/{orderId}/communications')
.onWrite(event => {

    const payload = {
        notification: {
            title: 'New communication added',
            body: 'Check it out!'
        }
    };

    const getDeviceTokensPromise = admin.database().ref('/{pharmacyId}/userDevices/{deviceToken}').once('value');

    let tokensSnapshot;

    let tokens;

    return getDeviceTokensPromise.then(results => {
        tokensSnapshot = results;

        if (!tokensSnapshot.hasChildren()) {
            return console.log('There are no notification tokens to send to');
        }

        console.log('There are', tokensSnapshot.numChildren(), 'tokens to send to');

        tokens = Object.keys(tokensSnapshot.val());

        console.log('These are the tokens', tokens)

        return null;
    });
});

尽我所能,让我不断获得“ null”作为返回值。

非常感谢您的帮助,谢谢大家。

2 个答案:

答案 0 :(得分:1)

访问数据库时,不能像这样进行变量替换:

admin.database().ref('/{pharmacyId}/userDevices/{deviceToken}')

这些花括号实际上是被带走的。它们不像函数定义中的通配符那样工作。您将需要使用未声明的context参数,使用通配符的值构建一个字符串。首先,您需要这样声明函数:

exports.notificationForCommunicationAdded =
  functions.database.ref('/{pharmacyId}/orders/{orderId}/communications')
  .onWrite((change, context) => {

请注意,第一个对象是Change对象,第二个对象是上下文。

然后,您需要使用上下文来获取通配符值的保留:

const pharmacyId = context.params.pharmacyId
const orderId = context.params.orderId

然后,您需要使用它们来构建数据库的路径:

admin.database().ref(`/${pharmacyId}/userDevices/${deviceToken}`)

答案 1 :(得分:0)

我终于可以使用以下语法:

... const pharmacyId = context.params.pharmacyId;

admin.database()。ref(/ + pharmacyId + /userDevices)。once('value')。then((snapshot)=> {...

出于某种原因,道格·史蒂文森(Doug Stevenson)提供的语法对我不起作用。

相关问题