Quiero usar Google Cloud Functions para contar documentos en Firestore y mostrar un contador en la aplicación.
Así que tengo el siguiente código que está funcionando:
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)}); } });Ahora tengo el problema, necesito obtener el uid del usuario actual. No sé cómo hacer eso. Para Realtime firebase existe una posible solución con contexto, pero Google no la ha implementado para Firestore.
Si desea mantener un recuento para cada usuario, eso sería:
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)}); } });