Fahmi Sawalha
Fahmi Sawalha

Reputation: 622

cloud function using typrescript and if statment

hello I'm new to cloud functions and I want to ask if there is some why to get more than one topic in one if statement here is my cloud function :

import * as functions from 'firebase-functions';
import * as admin from 'firebase-admin';
admin.initializeApp();

const fcm = admin.messaging();

export const sendToTopic = functions.firestore
  .document("Doctor2019/{documentId}")
  .onCreate(async snapshot => {

    const payload: admin.messaging.MessagingPayload = {
      notification: {
        title: 'NEW POST!',
        body: `Click here to see New Post`,
        icon: 'your-icon-url',
        click_action: 'FLUTTER_NOTIFICATION_CLICK'
      }
    };

    return fcm.sendToTopic('Doctor2019', payload);
  });


the problem is that I have more than one topic what I want to do is to check the creation of document on other collections and send the notification based on that , I really don't know what to do , any help ?

Upvotes: 0

Views: 61

Answers (2)

Renaud Tarnec
Renaud Tarnec

Reputation: 83163

If I correctly understand your goal, you can use a {wildcard} in place of the document ID as well as in place of the collection ID. Then you use the context object to get the value of the collection ID as follows:

export const sendToTopic = functions.firestore
    .document("{collectionId}/{documentId}")
    .onCreate(async (snap, context) => {  // Note the addition of context

        const collectionId = context.params.collectionId;
        
        const payload: admin.messaging.MessagingPayload = {
            notification: {
                title: 'NEW POST!',
                body: `Click here to see New Post`,
                icon: 'your-icon-url',
                click_action: 'FLUTTER_NOTIFICATION_CLICK'
            }
        };

        return fcm.sendToTopic(collectionId, payload);
    });

In case you have root collections that should not trigger a message, just adapt your data model and make the collections that need to trigger a message subcollections of a specific document. Something like:

export const sendToTopic = functions.firestore
    .document("messagingTriggers/triggers/{collectionId}/{documentId}")
    .onCreate(async (snap, context) => {...});

Then any document creation in, for example, a users collection will not trigger the Cloud Function.

Upvotes: 0

Methkal Khalawi
Methkal Khalawi

Reputation: 2477

I see that you want to send messages to different topics on FCM that are tied to different documents creations.

You cannot use one function to achieve that as the Function is tied to document creation on a specific collection. what you will need to do is to create different functions to different collections.

Upvotes: 1

Related Questions