0
votes

I'm trying to write a Firebase Cloud function to show a push notification to the user. First, I create the notification in the Firestore Database, and then I call a Firebase Cloud Function to send a push notification to the user. The problem is that I don't really know how to pass parameters to the Cloud Function

I call the function like this:

import { sendNotificationToUser, sendNotificationToNonUser } from '../../api/PushNotification';

export function createNotification(values, callback) {
  return async dispatch => {
    try {
      ...
      const newNotificationRef = firestore().collection('notifications').doc(notId);

      const newNotification = await firestore().runTransaction(async transaction => {
        const snapshot = await transaction.get(newNotificationRef);
        const data = snapshot.data();

        return transaction.set(newNotificationRef, {
          ...data,
          ...values,
          id: notId,
          viewed: false
        });
      });

      if (newNotification) {
        if (values.reciever === null) {
          sendNotificationToNonUser(values.title, values.message);
          ...
        } else {
          sendNotificationToUser(values.title, values.message, values.reciever);
          ...
        }
      } else {
        ...
      }
    } catch (e) {
      ...
    }
  };
}

Then, on the PushNotification doc, I have this:

import axios from 'axios';

const URL_BASE = 'https://<<MyProjectName>>.cloudfunctions.net';
const Api = axios.create({
  baseURL: URL_BASE
});

export function sendNotificationToNonUser(title, body) {
  Api.get('sendNotificationToNonUser', {
    params: { title, body }
  }).catch(error => { console.log(error.response); });
}

export function sendNotificationToUser(title, body, user) {
  Api.get('sendNotificationToUser', {
    params: { title, body, user }
  }).catch(error => { console.log(error.response); });
}

And on my Cloud Functions index.js

exports.sendNotificationToUser = functions.https.onRequest((data, response) => {
  console.log('Params:');
});

How can I pass the params I send from the PushNotifications file to the respective Cloud Functions? I'm fairly new to Functions myself

1

1 Answers

2
votes

The request, response parameters (data, response in your case) are essentially Express Request and Response objects. You can use query property of request to get those query parameters as shown.

exports.sendNotificationToUser = functions.https.onRequest((request, response) => {
  console.log('Query Params:', request.query);
  // This will log the params objects passed from frontend
});

You can also pass information in the request body and then access it by request.body in Cloud function, but then you would have to use a POST request.