Firebase функционирует как получить массив значений из базы данных Firebase - PullRequest
0 голосов
/ 04 октября 2018

Я хочу получить массив всех пользователей моей базы данных во второй функции, которую я использую "" return admin.database (). Ref ("/ Usuarios"). Once ('value') ", чтобы мыМожно отправить уведомление всем этим пользователям. Как все пользователи могут получить во второй функции? Спасибо

У меня есть этот код:

let functions = require('firebase-functions');
let admin = require('firebase-admin');
admin.initializeApp();
exports.sendNotificationNewAd = functions.database.ref('/Alertas/{notiId}').onWrite((change, context) => {

    // Only edit data when it is first created.
    if (change.before.exists()) {
    return null;
    }
    // Exit when the 

data is deleted.
        if (!change.after.exists()) {
        return null;
        }


    //te escribe el json de el mensaje nuevo
    const afterData = change.after.val();
    console.log("afterData: ", afterData);

    //get lat and lng of Ad
    const name = afterData.name;
    console.log("Name: "+name);

    //get lat and lng of Ad
    const lat = afterData.lat;
    const lng = afterData.lng;
    console.log("Lat y Lng", "lat: "+lat+" lng: "+lng);

    //get lat and lng of Ad
    const adType = afterData.typeAd;
    console.log("Tipo: "+adType);

    //get the user id of the ad
    const notiId = context.params.notiId;
    console.log("notiId: ", notiId);

    const userId = afterData.userId;
    console.log("userId: ", userId);

   return admin.database().ref("/Usuarios").once('value')
    .then(snap => {
        const userName = snap.child("name").val();
        return console.log("userName: ", userName);
    });
 });

1 Ответ

0 голосов
/ 04 октября 2018

Похоже, это то, что вы спрашиваете:

exports.sendNotificationNewAd =
    functions.database.ref('/Alertas/{notiId}')
        .onCreate((noti_snap, context) => {

            //te escribe el json de el mensaje nuevo
            const notif = noti_snap.val();
            console.log("notif: ", notif);

            //get lat and lng of Ad
            const name = notif.name;
            console.log("Name: " + name);

            //get lat and lng of Ad
            const lat = notif.lat;
            const lng = notif.lng;
            console.log("Lat y Lng", "lat: " + lat + " lng: " + lng);

            //get lat and lng of Ad
            const adType = notif.typeAd;
            console.log("Tipo: " + adType);

            //get the user id of the ad
            const notiId = context.params.notiId;
            console.log("notiId: ", notiId);

            const userId = notif.userId;
            console.log("userId: ", userId);

            return admin.database().ref("/Usuarios").once('value')
                .then(snap => {
                    let children = [];
                    snap.forEach(child_snap => {
                        children.push(child_snap.val()); // build children
                    });

                    return children;
                })
                .then(children => {
                    children.map(child => {
                        let message = {
                            notification: {
                                title: "message",
                                body: "body"
                            },
                            token: child.device_token
                        }

                        admin.messaging().send(message).catch(console.log);
                    });

                    return null;
                })
                .then( () => { 
                    return notif.ref.remove(); // consume send request
                })
                .catch(console.log);
        });
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...