2
votes

Cannot get Firebase Cloud Functions for Firestore to trigger on onWrite of my collection. Trying to setup device to device push notification for chat app. Function is deployed and on Pay as you go plan, however, changes in document, updates or create in "chats" collection is not triggering. Firebase cloud messaging is supposed to send a push and write to the log. Neither is happening. Push is working with other sources.

Thanks for your help, wish device to device push notifications was easier, plan is to watch the chat document and fire push notifications on update or create of new conversation. Open to other ideas. Thanks

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

exports.sendNotification = functions.firestore
  .document('chats/{chatID}')
  .onWrite((data, context) => {
    // Get an object representing the document
    console.log('chat triggered');
    // perform desired operations ...

    // See documentation on defining a message payload.
    var message = {
      notification: {
        title: 'Hello World!',
        body: 'Hello World!'
      },
      topic: context.params.chatID
    };

    // Send a message to devices subscribed to the provided topic.
    return admin.messaging().send(message)
      .then((response) => {
        // Response is a message ID string.
        console.log('Successfully sent message:', response);
        return true
      })
      .catch((error) => {
        console.log('Error sending message:', error);
      });

  });

UPDATE: I'm using "firebase-functions": "^1.0.1"

UPDATED: Updated the code to reflect what we currently have deployed, still not working.

3
Do you see an error message in the Functions log?Renaud Tarnec
What do you exactly mean by "Can’t get the method to trigger a log statement either". In the Firebase console, in a browser (console.firebase.google.com), if you select "Functions" in the vertical menu and select the "LOGS" tab, you will see the log from the Functions.Renaud Tarnec
I'm not clear on the logs you're seeing. Do you see a log indicating sendNotification Function execution started?Bob Snyder
How are you writing the Firestore data at chats/{chatID}, code or the Firebase Console? If code, edit your post to include it.Bob Snyder
My question was about how you are writing to the Firestore database, not the log. Whatever method you use, do you see the data change in the Firebase Console Database tab?Bob Snyder

3 Answers

2
votes

There are chances you are using the old syntax (before V1.0) with the new library (v1.0). See the Migration Guide: https://firebase.google.com/docs/functions/beta-v1-diff and check the version in your package.json file.

In addition, note that a Cloud Function must always return a Promise (or if you cannot, at least a value, for asynchronous functions). See this documentation (and associated video) which explain that in detail: https://firebase.google.com/docs/functions/terminate-functions

You should modify you code this way:

If you are using Cloud Functions 1.0 or above:

exports.sendNotification = functions.firestore
    .document('chats/{chatID}')
    .onWrite((change, context) => {

Returning:

exports.sendNotification = functions.firestore
.document('chats/{chatID}')
.onWrite((change, context) => {
  // Get an object representing the document
   console.log('chat triggered');
  // perform desired operations ...

    // See documentation on defining a message payload.
    var message = {
      notification: {
        title: 'Hello World!',
        body: 'Hello World!'
      },
      topic: context.params.chatID.   //<- If you are using a CF version under v1.0 don't change here
    };

    // Send a message to devices subscribed to the provided topic.
    return admin.messaging().send(message).  //<- return the resulting Promise
      .then((response) => {
        // Response is a message ID string.
        console.log('Successfully sent message:', response);
        return true;    //<- return a value
      })
      .catch((error) => {
        console.log('Error sending message:', error);
        //return.  <- No need to return here
      });

});
1
votes

Your firebase-admin initialization syntax, admin.initializeApp(), suggests you are using Cloud Functions SDK version 1.0.x. The parameters for onWrite() have changed in version 1.0.x from earlier versions. You also need to return a Promise for asynchronous action admin.messaging.send(). The three needed corrections are noted below:

exports.sendNotification = functions.firestore
    .document('chats/{chatID}')
    .onWrite((data, context) => {  // <= CHANGE
      // Get an object representing the document
       console.log('chat triggered');
      // perform desired operations ...

        // See documentation on defining a message payload.
        var message = {
          notification: {
            title: 'Hello World!',
            body: 'Hello World!'
          },
          topic: context.params.chatID // <= CHANGE
        };

        // Send a message to devices subscribed to the provided topic.
        return admin.messaging().send(message)  // <= CHANGE
          .then((response) => {
            // Response is a message ID string.
            console.log('Successfully sent message:', response);
            return
          })
          .catch((error) => {
            console.log('Error sending message:', error);
            return
          });

});
0
votes

For me the issue was I was writing data that already existed in Firestore. The onWrite isn't triggered apparently if the data you're writing is exactly the same as what is there.