Firebase Funtions push notifications

Viewed 34

I'm new to firebase and there is something I can't do. I want to send a notification to the phone with firebase functions. I want to receive notifications on the phone when someone follows me. My Firebase collection is as in the photo. I want to access the Followers array and send its information with notification. The codes I could write are as follows. What do I need to add?

enter image description here

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

exports.sendPushNotification = functions.firestore.document('/users/{uid}').onCreate((snap, context) => {
  var values = snap.data();
  var token = values.fcmTokens;     
  
  var payload = {
    notification: {
      title: values.title,
      body: values.message
      }    
  }   
  
  return admin.messaging().sendToDevice(token, payload);
});
1 Answers

First, onCreate() function is triggered when a document is created. I assume followers array will be updated everytime someone follows a user? In that case you should be using onUpdate() that'll trigger the function when the document is updated. You can just check if length of followers array has changed in the update, if yes then send the notification as shown below:

exports.sendPushNotification = functions.firestore
  .document('users/{userId}')
  .onUpdate((change, context) => {
    const newValue = change.after.data();
    const previousValue = change.before.data();

    if (newValue.followers.length > previousValue.followers.length) {
      // followers count increased, send notification
      const token = newValue.fcmTokens;

      const payload = {
        notification: {
          title: "New Follower",
          body: "Someone followed you"
        }
      }

      await admin.messaging().sendToDevice(token, payload);
    }

    return null;
  });

Here, we send notification only if the followers field has changed since this function will trigger whenever any field in this user document is updated.

If you want to specify who followed the user, then you'll have to find the new UID added in followers array and query that user's data.


Firestore documents have a max size limit of 1 MB so if a user can have many followers then I'll recommend creating a followers sub-collection. Then you'll be able to use onCreate() on the sub-document path /users/{userId}/followers/{followerId}

Related