简体   繁体   中英

cloud functions firebase v9 runTransaction

this is my cloud function:

const { getFirestore, runTransaction, FieldValue } = require('firebase-admin/firestore')

exports.purchasesStatistics = functions.firestore
    .document('transactions/{purchaseId}')
    .onUpdate((snap, context ) => {
      if (snap.before.data().status === 'RECEIVED') {
        return '0'
      }
      let purchasePaid = snap.after.data().status === 'RECEIVED' ? true : false
      if (purchasePaid === false) {
        return '0'
      }
      let allPurchase = snap.after.data()
      functions.logger.log('allPurchase', allPurchase)
      let ref = getFirestore().collection('statistics').doc('checkout')
      return runTransaction(ref, (transaction) => {
        return transaction.get(ref).then((doc) => {
          functions.logger.log('documento atualizado:', doc.data())
          return '0'
        })
      })
    })

Buy, it's returning "runTransaction is not a function". What i'm doing wrong? Didn't find proper way to use runTransaction on firebase v9

It appears that you are using theadmin SDK for NodeJS. This SDK is initialized differently from the Web SDK V9 and the way you use the functions is also different. Here is a detailed guide on how to initialize the admin SDK from scratch. After trying to add or import the runTransaction() function as your sample code, I also received the same error message. I followed the getstarted guide in addition to the documentation example to properly use this function, by using it from the firestore object that is created:

const { initializeApp, applicationDefault, cert } = require('firebase-admin/app');
const { getFirestore } = require('firebase-admin/firestore');
const serviceAccount = require('/path-to-service-account'); //Path to your service account, depends on implementation

initializeApp({
    credential: cert(serviceAccount)
});

const fireDB = getFirestore();
fireDB.runTransaction(); //Use the relevant args

This additional page contains a different example for using transactions.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM