Ad

Event.params Evaluating To Undefined; Cant Access Event.params.post In Firebase Realtime Database Using Cloud Functions

I have tried every way i know to get this cloud function working but i don't know for what reason this cloud function evaluates event.params to be undefined.

My cloud functions is :-

'use-strict'

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

exports.sendNotification = functions.database.ref('posts/{post}').onWrite(event => {
  const payload = {
    notification: {
      title: "Title",
      body: event.params.post,
      icon: "default"
    }
  };

  return admin.messaging().sendToDevice(payload).then(result => {
    console.log("notification Sent")
  });

});

Error i am getting :-

sendNotification
TypeError: Cannot read property 'post' of undefined at exports.sendNotification.functions.database.ref.onWrite.event(/srv/index.js: 11: 23) at cloudFunction(/srv/node_modules / firebase - functions / lib / cloud - functions.js: 119: 23) at / worker / worker.js: 825: 24 at < anonymous > at process._tickDomainCallback(internal / process / next_tick.js: 229: 7)

My database has a direct child named 'posts'. Whenever i add a child into it say {post} the function triggers but i can't get the {post} value.

Ad

Answer

This is most probably because you are using an old syntax with a new version of the Firebase SDK for Cloud Functions.

Your syntax (.onWrite(event => {})) corresponds to the SDK version that is <= v0.9.1.

See https://firebase.google.com/docs/functions/beta-v1-diff?authuser=0#realtime-database

You can check the version of Cloud Function in the package.json file.

If it is confirmed that your version is > v1.0.0 you should adapt your code as follows:

exports.sendNotification = functions.database.ref('posts/{post}').onWrite((change, context) => {
  const payload = {
    notification: {
      title: "Title",
      body: context.params.post,
      icon: "default"
    }
  };

  return admin.messaging().sendToDevice(payload)
  .then(result => {
    console.log("notification Sent");
    return null;
  });

});
Ad
source: stackoverflow.com
Ad