node.js - Firebase 云函数脚本未运行

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

我的 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() 对于其他函数来说效果很好;每当调用这些函数时,它们都应该扫描具有与区域设置的“Regione”相同的“Regione”属性的所有用户,但是当执行代码时,它不会通过“console.log(“Leggo utenti”);”运行代码行,这里是 firebase 控制台输出:

Firebase console output

enter image description here

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

最佳答案

我建议您按如下方式重构您的云功能。您不需要:

a/执行 event.data.toJSON()。数据已可作为 JavaScript 对象使用 event.data.val()

b/查看“Nascosto” Node ,然后重新查询以获得 Regione 值。只需查询上层 Node ,即 "Locali/{IDLocale}"

c/获取所有 Utenti 并循环它们以查找具有该区域的 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

关于node.js - Firebase 云函数脚本未运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50306057/

相关文章:

node.js - 在 express 应用程序中测试默认错误处理程序会导致超时

firebase - Flutter:无法将 firebase_auth 包从 0.5.11 更新到 0.6.6

java - 带有从 firebase 到数据库的数据的 TextView 在屏幕上消失

google-cloud-platform - 带有私有(private) Google Cloud 存储库的 GKE 上的 ImagePullBackOff

google-app-engine - x-goog-iap-generated-response header 是什么意思?

javascript - 我的 html 中的第一个按钮不请求发布,但其他按钮工作正常

node.js - 如何在 Node.js 中使用 Socket.io 从客户端发送到路由文件

javascript - 为什么我的复制变量改变了 Node js中的原始值变量?

swift - 从 Collection View 中删除未选择的单元格

java - com.google.auth.oauth2.GoogleCredentials.createScoped 处出现 StackOverflowError(GoogleCredentials.java :222)