Cloud functions for Firebase child_added
I am trying to use Cloud functions for Firebase by creating a function that will add an alias when a new user is added to the database (not auth). From Firebase Documention I found that I need to use:
ref.on("child_added", function(snapshot, prevChildKey) {
//Something
})
but i cant even run this function. My code:
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
var ref = admin.database().ref("/users");
ref.on("child_added", function(snapshot, prevChildKey) {
console.log(snapshot)
})
Can anyone help me?
Update:
After working on it, this is now my code:
const functions = require('firebase-functions');
// Import Admin SDK
var admin = require("firebase-admin");
admin.initializeApp(functions.config().firebase);
var db = admin.database();
var ref = db.ref('users');
var childs = [];
var nicknames = [];
exports.newUser = functions.database.ref('users').onWrite(event => {
const data = event.data.val();
ref.on("child_added", function(snapshot, childKey) {
if (!childs.includes(childKey)) {
childs.push(childKey);
};
for (i in childs) {
if (childs[i] == null) {
childs.splice(i, 1);
};
};
});
ref.once("value", function(snapshot) {
for (i in childs) {
var child = data[childs[i]];
if (!child.hasOwnProperty("nickname")) {
console.log("Child does not have nickname: " + childs[i]);
ref.child(childs[i]).update({
nickname: "user"+childs[i]
});
};
};
});
});
Based on what Doug Stevenson answered, I still need to figure out how to do this only if a new child is added (new user)
+3
source to share
1 answer
I understood that. Here is the code I used:
const functions = require('firebase-functions');
var admin = require("firebase-admin");
admin.initializeApp(functions.config().firebase);
var childs = [];
var nicknames = [];
exports.newUser = functions.database.ref('users').onWrite(event => {
ref.on("child_added", function(snapshot, childKey) {
if (!childs.includes(childKey)) {
childs.push(childKey);
}
});
});
I would like it to be called only when a child is added, not every time something is written to the database (to limit usage)
0
source to share