Tuesday 23 May 2017

Cloud Function Firebase Notification

I am trying to fire a notification using Firebases functions. I can get it to console log stating a message has been fired but can't actually get the notification to work in the browser. Can anyone see a flaw?

const functions = require('firebase-functions');

const admin = require('firebase-admin');

admin.initializeApp(functions.config().firebase);
exports.newMessageAlert = functions.database.ref('/messages/{message}').onWrite((event) => {
    const message = event.data.val();

const getTokens = admin.database().ref('users').once('value').then((snapshot) => {
    const tokens = [];
    snapshot.forEach((user) => {
        const token = user.child('token').val();
        if (token) tokens.push(token);
    });
    return tokens;
});

const getAuthor = admin.auth().getUser(message.uid);

Promise.all([getTokens, getAuthor]).then(([tokens, author]) => {
    const payload = {
        notification: {
            title: `Hot Take from ${author.displayName}`,
            body: message.content,
            icon: author.photoURL
        }
    };

    admin.messaging().sendToDevice(tokens, payload).then((resp) =>{
        console.log("IT WORKED", resp);
    });
});
});



via Daviepark

No comments:

Post a Comment