Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

FIrebase Firestore onCreate Cloud Function Event Params Undefined

I have tried following Firebase's documentation and other SO posts to access a parameter value for a cloud function I've successfully deployed.

Unfortunately I've still been receiving a

Type Error: cannot read property 'id' of undefined

I've logged event.params and it is outputting as undefined, so I understand the issue, but am unsure how, syntactically, I'm supposed to derive the param value.

Below is my js code for reference:

exports.observeCreate = functions.firestore.document('/pathOne/{id}/pathTwo/{anotherId}').onCreate(event => {
  console.log(event.params);

  //event prints out data but params undefined...
  const data = event.data()

  var id = event.params.id;

  return admin.firestore().collection('path').doc(id).get().then(doc => {
    const data = doc.data();
    var fcmToken = data.fcmToken;

    var message = {
      notification: {
        title: "x",
        body: "x"
      },
      token: fcmToken
    };

    admin.messaging().send(message)
      .then((response) => {
        console.log('Successfully sent message:', response);
        return;
      })
      .catch((error) => {
        console.log('Error sending message:', error);
        return;
      });

      return;
  })
})
like image 879
Chris Avatar asked Jun 15 '18 19:06

Chris


1 Answers

You're using the pre-1.0 API for the firebase-functions module, but the acutal version of it you have installed is 1.0 or later. The API changed in 1.0. Read about the changes here.

Firestore (and other types of) triggers now take a second parameter of type EventContext. This has a property called params that contains the data that used to be in event.params.

exports.observeCreate = functions.firestore.document('/pathOne/{id}/pathTwo/{anotherId}').onCreate((snapshot, context) => {
  console.log(context.params);
  console.log(context.params.id);
});

Please also read the documentation for the most up-to-date information about Firestore triggers.

like image 83
Doug Stevenson Avatar answered Oct 20 '22 03:10

Doug Stevenson