skip to Main Content

I am able to send notifications to android and apple devices using the "Compose notification" on firebase.
firebase compose notification pic

I am trying to send a message using cloud functions but I am having a hard time.

I can see all the data I want from the following code snip (cloud function)

const functions = require("firebase-functions");
const admin = require("firebase-admin");
admin.initializeApp();


exports.onUpdate = functions.firestore
    .document("chat messages/{docId}")
    .onCreate((snapshot, context) => {
      console.log("1");
      console.log(snapshot.data());
      console.log("2");
      console.log(snapshot.data()["User id"] );
      console.log(snapshot.data()["Chat message"] );

      console.log("3");
    });

now I need to target the phone to send the notification.
How do I do this?

2

Answers


  1. Chosen as BEST ANSWER

    here is the solution that worked for me

    /*
    to fix issues:
    (cd functions && npx eslint . --fix)
    to upload code:
    firebase deploy
    to do both:
    (cd functions && npx eslint . --fix)
    firebase deploy
    */
    
    
    const functions = require("firebase-functions");
    const admin = require("firebase-admin");
    // eslint-disable-next-line max-len
    const tokens = ["REDACTED_TOKEN"];
    
    admin.initializeApp();
    
    exports.onCreate = functions.firestore
        .document("chat/{docId}")
        .onCreate((snapshot, context) => {
          console.log(snapshot.data());
          console.log("fake data");
        });
    
    exports.onUpdate = functions.firestore
        .document("chat messages/{docId}")
        .onCreate( (snapshot, context) => {
          const payload = {
            // eslint-disable-next-line max-len
            notification: {title: "Push Title", body: "Push Body", sound: "default"},
            // eslint-disable-next-line max-len
            data: {click_action: "FLUTTER_NOTIFICATION_CLICK", message: "Sample Push Message"},
          };
    
          try {
            admin.messaging().sendToDevice(tokens, payload);
            console.log("NOTIFICATION SEND SUCCESFULLY");
          } catch (e) {
            console.log("ERROR SENDING NOTIFICATION");
            console.log(e);
          }
        });
    
    

  2. Did you see the FCM documentation on sending messages, specifically on sending to a specific device?

    I also recommend having a look at the Cloud Functions sample on notifying the user when something interesting happens. While it triggers on the Realtime Database instead of Firestore, the approach will be very similar to what you need.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search