LazyTurtle
LazyTurtle

Reputation: 105

Flutter Google Cloud Functions Get UID of Firestore trigger

i want to use Google Cloud Functions to count documents in firestore and show a counter in the app.

So I have the following code which is working:

const functions = require('firebase-functions');
const admin = require('firebase-admin');
const {FieldValue} = require("@google-cloud/firestore/build/src");

admin.initializeApp(functions.config().functions);
const doc = admin.firestore().collection('users').doc('CF7FOjfZ0iOlwXBc59AAEM7Qx1').collection('user').doc('general');


exports.countDocs = functions.firestore
    .document('/users/CF7FOjfZ0iOlwXBc59AAEM7Qx1/trainings/{trainings}')
    .onWrite((change, context) => {


        if (!change.before.exists) {
            // New document Created : add one to count
            doc.update({numberOfDocs: FieldValue.increment(1)});
        } else if (change.before.exists && change.after.exists) {
            // Updating existing document : Do nothing
        } else if (!change.after.exists) {
            // Deleting document : subtract one from count
            doc.update({numberOfDocs: FieldValue.increment(-1)});
        }
    });

Now I have the problem, that I need to get the uid of current user. I don't know how to do that. For Realtime firebase there is a possible solution with context, but Google has not implemented this for Firestore.

Upvotes: 0

Views: 156

Answers (1)

Frank van Puffelen
Frank van Puffelen

Reputation: 598728

If you want to keep a count for each user, that'd be:

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

exports.countDocs = functions.firestore
.document('/users/{uid}/trainings/{trainings}')
// Capture uid here 👆
.onWrite((change, context) => {
    const doc = admin.firestore().collection('users').doc(context.params.uid).collection('user').doc('general');
                            // User uid here 👆

    if (!change.before.exists) {
        // New document Created : add one to count
        doc.update({numberOfDocs: FieldValue.increment(1)});
    } else if (change.before.exists && change.after.exists) {
        // Updating existing document : Do nothing
    } else if (!change.after.exists) {
        // Deleting document : subtract one from count
        doc.update({numberOfDocs: FieldValue.increment(-1)});
    }
});

Upvotes: 3

Related Questions