I am using Firebase Cloud Function to send FCM upon Real-Time Database Triggered event. How can I get the value of a child ('uid') inside of {followerUid}?
exports.sendFollowerNotification = functions.database.ref('/followers/{followedUid}/{followerUid}').onWrite(event => {
const followerUid = event.params.followerUid;
const followedUid = event.params.followedUid;
I know exactly what you are looking for...
var uid = event.data.val();
var uid1 = String(uid);
add this uid1 to title or body
const payload = {
notification: {
title: paypes
body: uid1
}
};
I'm not sure I understand what you're trying to do but will take a stab.
If you are looking to access the data of uid inside the node that triggered the function:
var uid = event.data.child("uid").val;
Have a look at the documentation on handling event data.
Due to recent change in the API.
Following give the data value.
event.before.val();
or
event.after.val();
As onWrite(), which triggers when data is created, updated, or deleted in the Realtime Database.
So it gives both before and after value.
Related
I designed a flutter application using dart and firebase backend. I want to get triggered when a user creates, delete, or updates anything in the database. I understood onCreate,onRemoved, and onUpdate methods.
I wrote a javascript code in the firebase cloud function. I need to send a notification when a trigger happens. I don't want to use 3 different triggers. I want to use onWrite trigger only.
This is my database.
There are four departments called comp, civil, elect, and mech. I want to get triggered when database changes happen in a single onWrite trigger!
My First question is, I want to differentiate whether it is created or delete or update from onWrite trigger. I know it will trigger for all 3 events. But how can I differentiate it?
This is my code for onCreate...
exports.noticeAddedComp = functions.database.ref('main/notices/comp/{id}').onCreate( async evt => {
var token = ['dxnfr3dq6_Y:APA91bHavtoP62l296qzVoBhzQJbMFA']
const payload = {
notification:{
title : 'Message from Cloud',
body : 'This is your body',
sound : 'default'
},
data:{
message : 'Thi is new Push',
click_action : 'FLUTTER_NOTIFICATION_CLICK',
}
};
await admin.messaging().sendToDevice(token,payload);
});
Above code is working. But it is for onCreate.
My second question is, Do I need to write four onWrite trigger codes for four departments?
You can use the change.before and change.after properties to determine whether the node was created, deleted, or updated in a onWrite handler:
exports.noticeAddedComp = functions.database.ref('main/notices/comp/{id}')
.onWrite( async (change, context) => {
if (!change.before.exists()) console.log("New node: "+change.after.key);
if (!change.after.exists()) console.log("Deleted node: "+change.before.key);
if (change.before.exists() && change.after.exists()) console.log("Updated node: "+change.after.key)
...
});
You can attach a Cloud Function to all departments at once, by including another parameter into its path:
exports.noticeAddedComp = functions.database.ref('main/notices/{dept}/{id}')
.onWrite( async (change, context) => {
console.log("Triggered for department: "+context.params.dept);
...
})
You can check if
evt.after.data().property;
is either null or doesn't exist, meaning it is deleted.
EDIT:
Scenario when you create something (document or field) :
Creation of the field would mean that the field in "before" doesn't exist at all, and in "after" it exists, but can be null.
Scenario when you update something
Field in the "before" is not the same as the one in "after".
So I am very new to Firebase and also this is the first time I use TypeScript (no JavaScript experience either), and here is what I try to do. I have a JSON structure that I want my cloud function to add to database every time some action happens. My question is the following - could you point me to the right direction, on where I can get info besides official documentation, maybe some code examples would be great. Here is the JSON format I want to push to database. I want this to appear just like Firebase structures data in the console, nested nodes etc.
{
'Player': {
'id':'name',
'visible': {
'place': 'a1',
'sign': 'rock'
}
}
}
In your cloud function, you can use code like this to update the database:
const functions = require("firebase-functions");
const admin = require("firebase-admin");
admin.initializeApp();
// In your function
//##########################################
var playerRef = admin.database().ref('/Player');
// You can group multiple updates in an object
var updates = {};
updates['id'] = 'name';
updates['visible'] = {
place: 'a1',
sign: 'rock'
};
// Make sure to return the promise
return playerRef.update(updates);
//##########################################
I want a function to be called whenever a new child is added to "chat". I know this can be done using "child_added" event. However, from that function, I want to modify the newly created child.
So suppose a new child "123456" is added to chat and I want to update the "123456" object in the DB. I think I could solve the problem if I somehow manage to get the key (in this case it's 123456) of the newly added object. Is there a way to achieve this?
That should do the trick:
ref.on('child_added', function(childSnapshot, prevChildKey) {
var key = childSnapshot.key;
...
});
You will find more info at:
https://firebase.google.com/docs/reference/js/firebase.database.Query#on
u can also use firebase cloud functions as well by putting a trigger, so that this can be handled by server.
export const onNewChatTrigger = functions.database.ref('chat/{chatId}').onCreate(event => {
let key = event.params.chatId;
let data = event.data.val();
...
});
I'm using the .push method on firebase to write new records. I'd like to save the key where the new record is saved to the record itself at the id key. Currently, I do this in 2 operations, first push the record and then update using the ref returned. Can I do this in 1 write? Does it not matter?
If you invoke the Firebase push() method without arguments it is a pure client-side operation.
var newRef = ref.push(); // this does *not* call the server
You can then add the key() of the new ref to your item:
var newItem = {
name: 'anauleau'
id: newRef.key()
};
And write the item to the new location:
newRef.set(newItem);
There's no method to do this in one operation. However, it typically does not matter, because you can always get the push id from the .key() method on the DataSnapshot.
But, there's nothing wrong either about storing the push id. So you coul create a function on the Firebase prototype.
Firebase.prototype.pushWithId = function pushWithid(data) {
var childRef = this.push();
data.key = childRef.key();
childRef.update(data); // or .set() depending on your case
return childRef;
};
var ref = new Firebase('<my-firebase-app>');
ref.pushWithId({ name: 'Alice' });
Take caution with modifying the prototype of functions you do not own. In this case, you'll likely be fine. This method does little, and there's not much of a chance that the Firebase SDK gains a .pushWithId() method.
When using push() with Firebase, Firebase generates a unique ID, such as -JZl_BbXymAnOCPppMzN. I'm trying to figure out if there's any way to get that ID into the item I'm pushing during that first push(). For example, say I'm pushing an item as such:
var uid = "notset";
uid = fb.push({Name: name, Status: status, Position: position, UID: uid});
In this example, uid.name() holds my unique ID. So my first thought was to then update the item with the unique ID I now know, like:
var uidname = uid.name();
fb.child(uid.name()).update({UID: uidname});
And this does work.
However, I'm also relying on an on() to detect children added so I can deal with them as they arrive. For example:
fb.on('child_added',function(dataSnapshot) {
var newstatus = dataSnapshot.val();
var status = newstatus.Status;
var name = newstatus.Name;
var position = newstatus.Position;
var uid = newstatus.UID;
console.log
("Name: "+name+", Status: "+status+", Position: "+position+", UID: "+uid);
});
But because of the async nature of Firebase, this on() runs after the push() but before the update(). So my console.log() prints out a uid of notset instead of the correct UID.
Is there a different strategy I should be following? I suppose I can generate my own UIDs and push them to Firebase using firebaseRef.child('myUID').set(), but it seems there must be an easier way?
Firebase's push is a client-side operation, so nothing is sent to the server yet.
Instead of calling push with the data in one go, you can you split it into two separate calls:
var ref = fb.push();
/* use ref.name() here*/
ref.set({Name: name, Status: status, Position: position, UID: uid});
Not sure of this will work, but try this:
In fb.push, do not set the UID at all, leave it blank and firebase will generate it.
In fb.on, instead of newstatus.UID use dataSnapshot.name()