Firebase Cloud Function not trigging - using onCreate - Google Cloud Console

Viewed 60

I have searched multiple answers on stackoverflow but cannot seem to find one to solve my problem. I am trying to get my cloud function to run when I create certain new data in Firebase Realtime Database.

Screenshot of Database

The function deploys fine and shows no errors, but the problem is that when I add data (like the data in the attachment), the function isn't triggered? The data is created new, not updated.

Here is the code function:

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

exports.pushNotificationFromAdmin = functions.database.ref('pushNotifications/{createdID}').onCreate((snapshot, context) => {
  const data = snapshot.val();
  const topic = data.pushGroup.toString();
  const title = data.pushTitle;
  const body = data.pushBody;

  const payload = {
          notification : {
              title: title,
              body: body,
              mutable_content: 'true',
          },
  };

  const options = {
            priority : 'high',
            timeToLive : 60 * 60 * 2
  };
  console.log('Payload is : ' + payload)
  console.log('Sending to Topic ' + topic)
  return admin.messaging().sendToTopic(topic, payload, options);

});

What am I missing?

Thanks

1 Answers

You can refer to the Documentation where mentioned as :

When handling a Realtime Database event, the data object returned is a DataSnapshot. For onWrite or onUpdate events, the first parameter is a Change object that contains two snapshots that represent the data state before and after the triggering event. For onCreate and onDelete events, the data object returned is a snapshot of the data created or deleted.

In this example, the function retrieves the snapshot for the specified path as snap, converts the string at that location to uppercase, and writes that modified string to the database:

// Listens for new messages added to /messages/:pushId/original and creates an
// uppercase version of the message to /messages/:pushId/uppercase
exports.makeUppercase = functions.database.ref('/messages/{pushId}/original')
    .onCreate((snapshot, context) => {
      // Grab the current value of what was written to the Realtime Database.
      const original = snapshot.val();
      functions.logger.log('Uppercasing', context.params.pushId, original);
      const uppercase = original.toUpperCase();
      // You must return a Promise when performing asynchronous tasks inside a Functions such as
      // writing to the Firebase Realtime Database.
      // Setting an "uppercase" sibling in the Realtime Database returns a Promise.
      return snapshot.ref.parent.child('uppercase').set(uppercase);
    });

If you want to get more idea how to use triggers effectively for a realtime database , you can refer to this answer and this blog.

Related