【问题标题】:Firebase cloud functions script not runningFirebase 云功能脚本未运行
【发布时间】:2018-05-12 12:07:43
【问题描述】:

我的 firebase 数据库中有两个对象:

语言环境:

"39A81620-80EB-411B-80E2-C482824B7EF5" : {
      "Abilitato" : true,
      "Cap" : "00193",
      "Città" : "Roma",
      "ColoreFont" : "Bianco",
      "ColorePagina" : "Nero",
      "Descrizione" : "",
      "EmailLocale" : "test@gmail.com",
      "Font" : "Deco Future Black",
      "ImmagineCopertina" : "test_image",
      "Indirizzo" : "Via Dei Cosmati 3",
      "Latitudine" : 41.9053562,
      "Longitudine" : 12.4732003,
      "Nascosto" : false,
      "Nome" : "GUS",
      "PaginaFacebook" :"",
      "Proprietario" : "Eoh5yGzaPxWtZRiq7HAZL5WRu592",
      "Regione" : "Lazio",
      "SitoWeb" : "",
      "Telefono" : "06 8692 9033"
    }

和乌腾特:

"DDyGMUkbWjf8ucEQxNaxvI1wWPS2" : {
      "Cellulare" : "3300000000",
      "Citta" : "Roma",
      "Cognome" : "Zollo",
      "Compleanno" : 864597600,
      "ConversioniRimaste" : 2,
      "FBLiked" : false,
      "FBShared" : false,
      "ImmagineProfilo" : "https://firebasestorage.googleapis.com/v0/b/hangover-e0428.appspot.com/o/Utenti%2FDDyGMUkbWjf8ucEQxNaxvI1wWPS2%2FFoto%2FImmagineProfilo%2FImmagineProfilo.jpg?alt=media&token=5e31ef8f-7ab5-4bee-aa48-8ee0687a23f1",
      "LikeTotali" : 0,
      "Nome" : "Davide",
      "NuoviLike" : 0,
      "Privacy" : false,
      "PuntiHangover" : 0,
      "Regione" : "Lazio",
      "Sesso" : "Maschio",
      "isPR" : false,
      "token" : "eiL9ca2vXw8:APA91bFK4LHawfdqm_z0Ok0gRl-wHGaVhVjqNhjUXQtIJDqwqEAOKbJRUG1q8DkoviCBV1k4rYLlqmlCXaWiZQDBemJKH4rTb9sACawLs8D_7GE_TexmwHspYc8GsWxRAkPrjT3NbsUN"
    }

每当区域设置从隐藏变为可见时,“Nascosto”属性从 true 变为 false 时,我想通知用户区域设置如此开放,所以我有这个云功能:

//Rileva quando un locale passa da nascosto a visisbile e manda una notifica a tutti gli utenti della regione
exports.riAperturaLocale = functions.database.ref("Locali/{IDLocale}/Nascosto").onWrite(event =>{

    let stato_apertura = event.data.toJSON(); // valore di apertura o chiusura
    let ID_Locale = event.params.IDLocale;
    let nascosto = Boolean(stato_apertura);

    if(!nascosto) // il locale sta aprendo
    {
        console.log("Il Locale sta aprendo...")
        let locale = admin.database().ref("Locali").child(ID_Locale).once('value');
        return locale.then(snap =>{

            let dati_locale = snap.val();
            let regione = dati_locale["Regione"];

            ottieniUtentiRegioneLocale(dati_locale,regione);
        })

    }else{
        console.log("Il Locale sta chiudendo...:");
    }

    return 0;

})

//Ottiene un elenco di utenti nella regione del locale passato come parametro
function ottieniUtentiRegioneLocale(Locale,RegioneLocale){

    console.log("Notifico utenti per apertura locale...");

    let tutti_utenti = admin.database().ref("Utenti").once('value');
    return tutti_utenti.then(snap =>{

        console.log("Leggo utenti");
        var da_notificare = []// contiene gli Utenti da notificare

        snap.forEach((child) => {

            console.log("confronto utenti...");

            let IDUtente = String(child.key); // ID dell'Utente corrente
            let ValoriUtente = child.toJSON(); //Valori dell'utente che si sta scansionando

            let regione_user = ValoriUtente["Regione"];

            if(regione_user == RegioneLocale){
                da_notificare.push(IDUtente);
            }
        })

        if(da_notificare.length != 0){

            da_notificare.forEach((user) => {

                let img = Locale["ImmagineCopertina"];
                // creo la notifica 
                let testo = Locale["Nome"] + " " + "di" + " " + Locale["Città"] + " ha aperto, " 
                + "entra a scoprire tutti gli Eventi!"; 

                notificaUtente(user,"Un nuovo Locale ha aperto!",testo,img,"notifica");

            })

        }else{
            console.log("Non ci sono utenti da notificare...");
        }

    })

}

//Invia una notifica all'Utente passato come parametro
function notificaUtente(IDUtente,titolo,testo,URL,tipo){

    console.log("mando notifica a: " + IDUtente);

    let TokenDispositivo = admin.database().ref("Utenti").child(IDUtente).child("token").once('value');
    return TokenDispositivo.then(snap =>{

        let token = String(snap.val());

        // Notification details.
        const payload = {
             notification: {
                title: titolo,
                body: testo,
                sound: 'default',
                badge:"1"
            },
            data:{"tipo":tipo,
                    "url":URL,
                "testo":testo,
                "titolo":titolo,
            "mittente":IDUtente}
        };

        admin.messaging().sendToDevice(token, payload).then(response => {
            const error = response.error;
            if (error){
                console.log("Errore notifica" + error);
            }
        })
    })
}

请注意,notificaUtente() 对其他函数工作正常;每当调用这些函数时,它们应该扫描所有具有与 Locale 的“Regione”相同的“Regione”属性但在执行代码时它不会运行通过“console.log("Leggo utenti");”的用户。一行代码,这里是firebase控制台输出:

Firebase console output

为什么?我是 node.js 的新手,我需要一点帮助,谢谢。

【问题讨论】:

    标签: node.js firebase firebase-realtime-database google-cloud-functions


    【解决方案1】:

    我建议你重构你的云函数如下。你不需要:

    a/ 执行 event.data.toJSON()。数据已作为 JavaScript 对象提供,event.data.val()

    b/ 查看“Nascosto”节点,然后重新查询以获得 Regione 值。在上层节点上查询即可,即"Locali/{IDLocale}"

    c/ 获取所有 Utenti 并遍历它们以找到具有该区域的那些。只需构建一个查询即可获取它们。

    exports.riAperturaLocale = functions.database.ref("Locali/{IDLocale}")
    .onWrite(event => {
        const ID_Locale = event.params.IDLocale;
        const nascosto = event.data.val().Nascosto;
    
            if (!nascosto) {   // il locale sta aprendo
    
                const regione = event.data.val().Regione;
    
                const query = admin.database().ref("Utenti").orderByChild('Regione').equalTo(regione).once('value');
    
                return query.once('value').then(snap => {
    
                    const notificationPromises = [];
    
                    snap.forEach(childSnapshot => {
    
                        const userKey = childSnapshot.key;
    
                        const token = childSnapshot.val().token;
    
                        const img = Locale["ImmagineCopertina"];
                        // creo la notifica
                        const testo = Locale["Nome"] + " " + "di" + " " + Locale["Città"] + " ha aperto, "
                            + "entra a scoprire tutti gli Eventi!";
    
                        const titolo = 'Un nuovo Locale ha aperto!';                      
    
                        const payload = {
                                    notification: {
                                        title: titolo,
                                        body: testo,
                                        sound: 'default',
                                        badge:"1"
                                    },
                                    data:{tipo: 'notifica',
                                        url: img,
                                        testo: testo,
                                        titolo: titolo,
                                        mittente:userKey
                                    }
                                };
    
                        const p = admin.messaging().sendToDevice(token, payload);
                        notificationPromises.push(p);
    
                    });
    
                    return Promise.all(notificationPromises);
    
                }).catch(error => {
                    console.log(error);
                    //other error treatment
                });
    
            } else {
                console.log("Il Locale sta chiudendo...:");
                return false;
            }
    
        });
    

    Firebase 团队的视频: https://www.youtube.com/watch?v=7IkUgCLr5oA&list=PLl-K7zZEsYLkPZHe41m4jfAxUi0JjLgSM&index=1https://www.youtube.com/watch?v=652XeeKNHSk&index=2&list=PLl-K7zZEsYLkPZHe41m4jfAxUi0JjLgSMhttps://www.youtube.com/watch?v=d9GrysWH1Lc&index=3&list=PLl-K7zZEsYLkPZHe41m4jfAxUi0JjLgSM

    最后一点:请注意,Cloud Functions 已更新至 1.0.x 版本,并且语法已更改。您可以根据本文档调整您的功能代码:https://firebase.google.com/docs/functions/beta-v1-diff

    【讨论】:

    • 已编辑问题 ;) 现在脚本工作正常,但它没有按预期发送通知,可能是承诺有问题?
    • @GiulioSerra 我已经调整了答案。希望它会有所帮助。您应该按照我建议的第三个视频中的说明返回Promise.all()。还有一个“小”点:这段代码中的大部分变量都可以声明为const,不需要声明为let
    • 非常感谢,我感觉到一些重构即将到来;)
    • @GiulioSerra 很高兴知道我可以提供帮助。如果您认为我的回答“有帮助且经过充分研究”(请参阅​​ stackoverflow.com/help/someone-answersstackoverflow.com/help/privileges/vote-up),您可以通过单击答案左侧的大向上箭头来投票。谢谢;)
    猜你喜欢
    • 2019-10-15
    • 1970-01-01
    • 2020-11-02
    • 2017-08-03
    • 2021-10-26
    • 1970-01-01
    • 2021-11-27
    相关资源
    最近更新 更多