Ways to collect particular tokens for delivering targeted push notifications to designated devices

When filtering the user's contacts, I ensure that only contacts with created accounts are displayed on the screen. This process helps in visually organizing the contact list.

 List<PhonesContacts> phoneContacts = snapshot.data;
              List myContacts = [];
              
              for (var j = 0; j < phoneContacts.length; j++) {
                myContacts.contains(phoneContacts[j])
                 ? null
                 : myContacts.add(phoneContacts[j]);

              }

Query: Do I need to replicate the above process in the backend using cloud functions to filter the user's tokens before sending notifications to their contacts? Alternatively, is there a way to pass the myContacts array from frontend to backend for direct token filtering?

In my current cloud function setup, all tokens receive notifications regardless of whether they are relevant contacts or not. How can this function be modified to target specific users based on the frontend filtered contacts?

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

const db = admin.firestore();
const fcm = admin.messaging();


export const sendToDevice = functions.firestore
  .document('stat/{statId}')
  .onUpdate(async change => {


   const data = change.after.data();

   const currentUser = await db 
      .collection("profile")   
      .doc(data.uid)         
      .get();

   const name = currentUser.get("name");

   const querySnapshot = await db
      .collection('tokens')
      .get();
    
   /* Here, I would implement contact filtration and token retrieval OR explore passing pre-filtered contacts from the frontend for token inclusion */

    const tokens = querySnapshot.docs.map(snap => snap.data().token);


    const payload: admin.messaging.MessagingPayload = {
      notification: {
        title: name,
        body: data.stat,
        click_action: 'FLUTTER_NOTIFICATION_CLICK'
      },
      data: {
         click_action: 'FLUTTER_NOTIFICATION_CLICK',
         title: name,
         body: data.stat
      }
    };

    return fcm.sendToDevice(tokens, payload);
  });

Answer №1

I stumbled upon a fantastic tool that enables seamless communication between the front end and back end. It's all thanks to the cloud_functions flutter package, which you can check out here:

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to implement an Angular Guard that utilizes an API service for validation and redirects in case of failure?

Hello there! I am currently working on an Angular 7 application that deals with time cards. One of the main features I have implemented is a CanActivate Guard for controlling access to certain components. The CanActivate code utilizes Observables to decid ...

Setting up Firebase for a specific sub-application located in a designated folder

After using Firebase hosting to host my app in the root directory, I now want to serve a separate codebase for my forum on I have set up two targets: one for my main app in one repository and another for the forum in a separate repository. Additionally, I ...

Using Handlebars.js with Angular CLI versions 6 and above: A Step-by-Step Guide

Looking to create a customizable customer letter in either plain text or HTML format that can be edited further by the customer. Considering using Handlebars.js to render an HTML template with mustache tags, using a JSON object for business information. T ...

Steps to develop a collaborative NPM package

I am currently in the process of developing an NPM package using Typescript that contains solely my type interfaces. At the moment, my project has the following folder structure: project │ index.ts │ └───types │ restaurant.ts │ ...

The present URL of Next.js version 13

When working with Next.js App Router in SSR, how can I retrieve the complete URL of the current page? I am unable to use window.location.href due to the absence of a defined window object, and using useRouter() does not provide access to the full URL. ...

"Slow loading times experienced with Nextjs Image component when integrated with a map

Why do the images load slowly on localhost when using map, but quickly when not using it? I've tried various props with the Image component, but none seem to solve this issue. However, if I refresh the page after all images have rendered once, they ...

Prevent Component Reloading in Angular 4 when revisiting the page

My application consists of three main components: 1) Map 2) Search 3) User Profile Upon logging in, the MAP component is loaded by default. I can navigate to other screens using the header menu link. I am looking to implement a feature where the map comp ...

Eliminating pre-set CSS styles injected in Angular 2/Ionic 2 automatically

I'm encountering an issue where adding the ionic 2 gesture (press) to a button results in inline styles being automatically applied to that button. Is there a way to override the styles it adds? Button <button ion-button (press)="toggleFavourite ...

Unable to assign a value to the HTMLInputElement's property: The input field can only be set to a filename or an empty string programmatically

When attempting to upload an image, I encountered the error message listed in the question title: This is my template <input type="file" formControlName="avatar" accept=".jpg, .jpeg .svg" #fileInput (change)="uploa ...

Using Typescript to Encapsulate the Assertion that Foo Belongs to a Specific Type

For the purpose of this demonstration, let's define two dummy classes and include some example code: class X { constructor() {} } class Y extends X { value: number; constructor(value: number) { super(); this.value = valu ...

Ensure that the JSON file containing translations is fully loaded prior to proceeding with the loading of the Angular application

In our Angular application, we have integrated internationalization using ng2-translate. We are utilizing the .instant(...) method for translations to simplify the process without having to subscribe to observables. One issue we are facing is that using . ...

A step-by-step guide to integrating a legend on a leaflet map using Angular and the ngx-leaflet plugin

I am attempting to integrate a legend into a map generated using Asymmetrik/ngx-leaflet. The tutorial I followed for creating the map can be found at https://github.com/Asymmetrik/ngx-leaflet. There are two distinct layers on the map, each requiring its ow ...

What is preventing me from using property null checking to narrow down types?

Why does TypeScript give an error when using property checking to narrow the type like this? function test2(value:{a:number}|{b:number}){ // `.a` underlined with: "Property a does not exist on type {b:number}" if(value.a != null){ ...

Error in GraphQL query: specified argument is mandatory, yet not supplied

I recently started learning about graphql and encountered an issue with my query. Here is the code I am using: { product { id } } "message": "Field "product" argument "id" of type "String!" is requir ...

In order to effectively manage the output of these loaders, it may be necessary to incorporate an extra loader. This can be achieved by using the

I'm currently working with react typescript and trying to implement a time zone picker using a select component. I attempted to utilize the npm package react-timezone-select, but encountered some console errors: index.js:1 ./node_modules/react-timezo ...

Looking to establish combinations in typescript? The answer lies in utilizing a discriminated union

I've been working with Typescript and I'm curious if it's possible to specify the valid combinations of input for a function. Below is a simplified version of the code: interface ActionType { type: string, payload: { count?: ...

Customizing the Android Back Button behavior in NativeScript for a single specific page

I am currently using NativeScript version 5.2.4 along with TypeScript. My goal is to disable the back button functionality in one specific page only, but I'm facing an issue where it also disables the back button behavior for child pages. Below is the ...

The presence of v-if does not depend on the model value to toggle the element

I have a scenario where I want to hide the dropdown menu for US states if a different country other than the US is selected. The code snippet I am using to achieve this functionality is shown below: <b-row v-for="demo in demographics" :key=&qu ...

Accessing HTTP data through a function instead of using ngOnInit in Angular is a more efficient approach

Trying to retrieve data from a service using setInterval has posed an issue for me. When I call the service from ngOnInit, everything functions as expected. However, when attempting to call it from any other function, an error occurs: "ERROR TypeError: Ca ...

What is the best way to transfer an image from Firebase storage to the Facebook Marketing API?

Could someone assist me in understanding how to download an image from Node/Express/Cloud Functions for Firebase? Currently, I'm only able to retrieve an object containing information about my image in Firebase storage (using getMetadata();) let ima ...