Ad

Firebase Cloud Function Is Not Being Executed On OnCreate Event For Firebase Real Time Database

I have deployed the next function to the firebase:

import * as functions from 'firebase-functions';
import * as admin from 'firebase-admin';

console.log('FILE INCLUDED');

const serviceAccount = require('../cargo-tender-firebase-adminsdk-8e307-c6b82762d2.json');

admin.initializeApp({
  credential: admin.credential.cert(serviceAccount),
  databaseURL: 'https://cargo-tender.firebaseio.com'
});

console.log('INITIALIZED');

export const onMessageCreate = functions.database
  .ref('/chat')
  .onCreate((snapshot, context) => {

    console.log('onCreate RUN');

    const token = 'myToken';
    const payload = {
        notification: {
        title: 'Title',
        body: 'come check it',
        badge: '0',
        sound: 'default',
        }
    };

    console.log('trying to send push notification');

    return admin
      .messaging()
      .sendToDevice(token, payload).then((response) => {
        console.log('Message sent');
        console.log(response);
      }).catch((error) => {
        console.error('There was an error, while sending the message');
        console.error(error);
      });
  });

  console.log('FUNCTION FINISH');

But when I try to create a record under path /user-chat - the function is not executed, the push notification is not being sent. Also, the function call is not being registered in the logs.

If I run the function manually from the firebase console (test function) - the function executes without errors. The push notification is received. And I see that is everything good in the logs:

3:07:56.902 PM onMessageCreate FILE INCLUDED
3:07:57.112 PM onMessageCreate INITIALIZED
3:07:57.113 PM onMessageCreate FUNCTION FINISH
3:07:57.273 PM onMessageCreate onCreate RUN
3:07:57.273 PM onMessageCreate trying to send push notification
3:07:57.757 PM onMessageCreate Message sent
3:07:57.759 PM onMessageCreate { results: [ { messageId: '0:1561550877745153%be2b376ebe2b376e' } ],
  canonicalRegistrationTokenCount: 0,
  failureCount: 0,
  successCount: 1,
  multicastId: 5684437879493655000 }
3:07:57.771 PM onMessageCreate Function execution took 1008 ms, finished with status: 'ok'

I don't get why the onCreate is not fired, when I add a record in the firebase under the specified path (/user-chat). I also tried to use another path, like /chat, but this did not do the trick.

Any advice on this would be really appreciated.

Thank you!

Ad

Answer

Fixed! I had to add a mask, e.g. /user-chat/{anything}

Ad
source: stackoverflow.com
Ad