1

Im trying to learn how to read the official firebase docs. but I cant seem to get it right

I want to send notifications from a cloud function to a phone, but I was only able to do it using some functions not found on the docs ( see code below )

I know the docs say to use getMessaging().send(message), but I cant get it to work {see image attached}

cloud function

code where I am able to send notification


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] https://firebase.google.com/docs/cloud-messaging/send-message

Alexander N.
  • 1,458
  • 14
  • 25
Juan Casas
  • 268
  • 2
  • 13

1 Answers1

1

You are probably interested in something like this:

const messaging = require("firebase-admin/messaging");

messaging.getMessaging() //continued with what you want to accomplish.

The firebase-admin node package has a sub packaging for messaging where getMessaging() lives, but the documentation also seems to note that getMessaging() is the equivalent of admin.messaging() so using getMessaging() would make your functions closer in line with the documentation. If you wanted to be even more similar to the documentation, you may want to switch from require to import to selectively load only the parts of the package you need. An example of using import instead of require may look like this:

import {getMessaging} from 'firebase-admin/messaging';
getMessaging().send(message);
Alexander N.
  • 1,458
  • 14
  • 25