Ilonpilaaja
Ilonpilaaja

Reputation: 1249

Firebase user authentication trigger that writes to realtime database

exports.setupDefaultPullups = functions.auth.user()
    .onCreate(
        async (user) => {
            const dbRef= functions.database.ref;
            let vl= await (dbRef.once('value').then( (snapshot) => {
                return snapshot.ref.child('userInfo/'+user.uid).set(18);
            }));
            return vl;
        }
    );

I am trying to write a trigger for some initial set-up for a new user, in Firebase. However, the above code does not work. What is wrong with it? Basically, upon registering a new user, I would like to set up his/her property "defaultPullUps" to, say, 18, using the above path.

EDIT: I am sorry for not giving details. Initially, there was an issue with the "async" keyword, that has been fixed by updating the node.js engine. Now, I get various error messages depending on how I tweak the code. Sometimes it says "... is not a function".

EDIT': Although I agree my question is not up to par, but there is a value in it: in online documentation of Firebase authentication triggers, how to access the "main" database is not shown https://firebase.google.com/docs/functions/auth-events

EDIT'': here is the entire message:

TypeError: Cannot read property 'child' of undefined
at exports.setupDefaultPullups.functions.auth.user.onCreate.user (/srv/index.js:15:36)
at cloudFunctionNewSignature (/srv/node_modules/firebase-functions/lib/cloud-functions.js:105:23)
at /worker/worker.js:756:24
at <anonymous>
at process._tickDomainCallback (internal/process/next_tick.js:228:7)

Upvotes: 0

Views: 1138

Answers (1)

Frank van Puffelen
Frank van Puffelen

Reputation: 599011

This line makes no sense:

const dbRef= functions.database.ref;

If you want to use the Firebase Realtime Database in a Cloud Function that is triggered from another source (such as Firebase Authentication in your case), you can do so by using the Firebase Admin SDK.

For an example of this, see the Initialize Firebase SDK for Cloud Functions section of the Get started with Cloud Functions documentation. Specifically, you'll need to import and initialize is using:

// The Cloud Functions for Firebase SDK to create Cloud Functions and setup triggers.
const functions = require('firebase-functions');

// The Firebase Admin SDK to access the Firebase Realtime Database.
const admin = require('firebase-admin');
admin.initializeApp();

And then can access the database from your function using:

const dbRef= admin.database().ref();

Upvotes: 1

Related Questions