【问题标题】:Undefined username in cloud functions?云功能中未定义的用户名?
【发布时间】:2019-06-19 14:20:36
【问题描述】:

我想向特定设备发送通知,因此我编写了此函数并使其正常工作,但我在用户名中未定义

日志输出:

得到这个

after: { '-LhjfwZeu0Ryr6jYRq5r': { Price: '888', date: '2019-6-19', description: 'Ghh', id: 50, nameOfProblem: 'Vbh', providerName: 'Loy', providerService: 'Carpenter', statusInfo: 'Incomplete', time: '15:22', username:"devas" }}

usernameundefined

这里是函数

exports.sendPushR = functions.database.ref('/request/{pid}/{uid}/orders')
    .onWrite(async (snapshot, context) => {
        const registrationTokens = "------";
        const providerId = context.params.pid;
        const userId = context.params.uid;
        const event = context.params;
        console.log("event", event);
        console.log(`New Order from ${userId} to ${providerId}`);
        const afterData = snapshot.after.val(); // data after the write
        const username = snapshot.after.val().username;
        console.log(afterData);
        console.log(username);
        const payload = {
            notification: {
                title: 'Message received',
                body: `You received a new order from ${username} check it now! `,
                sound: "default",
                icon: "default",
            }
        };


        try {
            const response = await admin.messaging().sendToDevice(registrationTokens, payload);
            console.log('Successfully sent message:', response);
        }
        catch (error) {
            console.log('Error sending message:', error);
        }
        return null;
    });

【问题讨论】:

  • 从您共享的数据来看,用户名似乎比您检索的更深
  • @FunKeyFlo 嗯,所以如何访问它们,因为父级是实时数据库生成的密钥

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


【解决方案1】:

看起来您编写的代码是为了在将新订单添加到数据库时运行。但是你已经声明它像这样触发:

exports.sendPushR = functions.database.ref('/request/{pid}/{uid}/orders')
    .onWrite(async (snapshot, context) => {

这意味着只要在orders 节点下为用户编写任何内容,代码就会触发。要仅在该orders 节点下写入订单时触发,请将您的触发器定义为:

exports.sendPushR = functions.database.ref('/request/{pid}/{uid}/orders/{orderid}')
    .onWrite(async (snapshot, context) => {

上面的区别是路径现在包含{orderid},这意味着它会在树中触发低一级,而您的snapshot.after 将不再包含-L 级别。


由于您实际上似乎只关心订单何时创建,因此您也只能在此触发(这意味着当订单更新或删除时您的函数不会被调用)。应该是这样的:

exports.sendPushR = functions.database.ref('/request/{pid}/{uid}/orders/{orderid}')
.onCreate(async (snapshot, context) => {
    ...
    const afterData = snapshot.val();
    const username = snapshot.val().username;
    console.log(afterData);
    console.log(username);
    ...
});

这里我们再次触发 JSON 中的较低级别。但是由于我们现在触发onCreate,我们不再有前后快照,而是只需执行snapshot.val() 即可获取刚刚创建的数据。

【讨论】:

  • 谢谢你,Frank,现在如果我们想深入定义“{orderid},{uid},{pid}”,我们说什么?
  • 我不明白你的意思。能否详细说明或换个说法?
  • 我的意思是路径中的{orderid},意思是触发器或firebase中的什么以及它如何知道它是orderid而不是userid?
  • {orderid} 只是声明该路径段使用什么名称。您可以将其称为 {whatever},只要您在其他任何地方都将其称为 whatever,它的工作原理也是一样的。
【解决方案2】:

由于您要检索的对象有一个生成的成员,您可以使用 for-in 循环来检索该值。

const object = snapshot.after.val()
for(const key in object) {
    if (object.hasOwnProperty(key)) {
        const element = object[key];
        if(element.username) {
             console.log(element.username);
             break;
        }  
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-03-12
    • 2019-08-05
    • 1970-01-01
    • 1970-01-01
    • 2019-12-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多