How to deploy function ? Check this link https://www.renjithplavada.com/2022/05/firebase-creating-and-deploying-cloud.html
Use Trigger 'onCreate' for newly pushed objects
Use Trigger 'onWrite' for every action - create, update or delete objects.
'use strict';
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();
//function name - SendNewNotification
exports.SendNewNotification = functions.database.ref('/notification/{uid}/').onWrite(event=>{
//get user uid
const uuid = event.params.uid;
//another method cost uid = event.data.val().userID
// const newData = event.after.val();
// const oldData = event.before.val();
console.log('User to send notification', uuid);
//get userid token
var ref = admin.database().ref('users/${uuid}/token');
return ref.once("value", function(snapshot){
const payload = {
notification: {
title: 'You have a message.',
body: 'Tap here to check it out!'
// sound: "default"
}
};
admin.messaging().sendToDevice(snapshot.val(), payload)
}, function (errorObject) {
console.log("The read failed: " + errorObject.code);
});
})
//to include options
// const options = {
// priority: "high",
// timeToLive: 60 * 10 * 1
// };
//admin.messaging().sendToDevice(snapshot.val(), payload,options).then(response => {
//console.log("Message Sent Successfully",response);
//return{success:};
//to compare
// if (newData != oldData && newData == 'yes') {
// admin.messaging().sendToDevice(snapshot.val(), payload)}
//to send to topic 'newitems'
//make sure topic are same in android and cloud functions
// FirebaseMessaging.getInstance().subscribeToTopic("newitems");
//return admin.messaging().sendToTopic("newitems", payLoad, options);
// or
//return admin.messaging().sendToTopic(snapshot.val()", payLoad, options);
exports.SendNewNotification = functions.database.ref('/notification/{uid}/').onCreate(event=>{
//If data changes to be compared
//exports.checkForNew = functions.database.ref('foo/{createdID}').onCreate((created_child, context) => {
//context.params.createdID to reference the ID of the created object in the database under 'foo'
//created_child.val() to reference any field values of the created objcet
});
Post a Comment