I recently deployed a function to Firebase with the following code:
import * as functions from 'firebase-functions';
import * as admin from 'firebase-admin';
console.log('FILE LOADED');
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 TRIGGERED');
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('Error occurred while sending the message');
console.error(error);
});
});
console.log('FUNCTION COMPLETE');
However, when I attempt to create a record under /user-chat
, the function does not run and the push notification is not sent. The logs also do not show the function being called.
If I manually trigger the function from the Firebase console (using test function), it runs without any issues, the push notification is received, and the logs display the expected output:
3:07:56.902 PM onMessageCreate FILE INCLUDED
3:07:57.112 PM onMessageCreate INITIALIZED
3:07:57.113 PM onMessageCreate FUNCTION COMPLETE
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 am unsure why the onCreate event is not being triggered when adding a record to /user-chat
. I have even tried using a different path, like /chat
, but that did not resolve the issue either.
Any insights or advice on this matter would be greatly appreciated.
Thank you!