Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cloud Functions for Firebase - write to database when a new user created

I am pretty new Cloud Functions for Firebase and the javascript language. I am trying to add a function every time a user created to write into the database. This is my code:

const functions = require('firebase-functions');
const admin = require('firebase-admin');

admin.initializeApp(functions.config().firebase);

exports.addAccount = functions.auth.user().onCreate(event => {
const user = event.data; // The firebase user
const id = user.uid;
const displayName = user.displayName;
const photoURL = user.photoURL;

return admin.database().ref.child("/users/${id}/info/status").set("ok");} );

what I am trying to do is every time a user signup to my app, the functions wil write into the database that his status is "OK". But my code dosn't work. enter image description here

what am I doing wrong?

like image 629
Idan Aviv Avatar asked Jun 11 '17 10:06

Idan Aviv


People also ask

How do I trigger a Firebase cloud function?

Cloud Firestore function triggersTriggered when a document is written to for the first time. Triggered when a document already exists and has any value changed. Triggered when a document with data is deleted. Triggered when onCreate , onUpdate or onDelete is triggered.

What is the difference between onCall and onRequest?

onRequest creates a standard API endpoint, and you'll use whatever methods your client-side code normally uses to make. HTTP requests to interact with them. onCall creates a callable. Once you get used to them, onCall is less effort to write, but you don't have all the flexibility you might be used to.


1 Answers

I found the problem. The problem is that shouldn't use the ${id}, and I shouldn't have use the child. So the code should look like this:

const functions = require('firebase-functions');
const admin = require('firebase-admin');

admin.initializeApp(functions.config().firebase);

exports.addAccount = functions.auth.user().onCreate(event => {
    const user = event.data; // The firebase user
    const id = user.uid;
    const displayName = user.displayName;
    const photoURL = user.photoURL;

    return admin.database().ref("/users/"+id+"/info/status").set("ok"); 
});
like image 95
Idan Aviv Avatar answered Oct 21 '22 06:10

Idan Aviv