Flutter Google Cloud Functions 获取 Firestore 触发器的 UID

Flutter Google Cloud Functions Get UID of Firestore trigger

我想使用 Google Cloud Functions 对 firestore 中的文档进行计数并在应用程序中显示一个计数器。

所以我有以下有效的代码:

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)});
        }
    });

现在我遇到了问题,我需要获取当前用户的 uid。我不知道该怎么做。对于 Realtime firebase,有一个可能的上下文解决方案,但是 Google 还没有为 Firestore 实现这个。

如果您想为每个用户保留一个计数,那就是:

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)});
    }
});