Search code examples
firebase-realtime-databasegoogle-cloud-functionsatomic

Atomic update of Realtime Database from Google Cloud Functions


I use Google Cloud Functions to create an API endpoint for my users to interact with the Realtime Database.

The problem I have is that I'm not sure how the code works. I have a helper function doSomething that I need to call only once, but I have a suspicion that there are cases where it can be called twice or possibly more (when multiple users call the API at the same time and the update operation hasn't been processed by the DB yet). Is it possible? Does it mean I need to use a transaction method? Thank you!


DB structure

{
  somePath: {
    someSubPath: null
  }
}

Google Cloud Functions code

const functions = require('firebase-functions')
const admin = require('firebase-admin')
const cors = require('cors')({origin: true});
admin.initializeApp(functions.config().firebase)

// API ENDPOINT
exports.test = functions.https.onRequest((req, res) => {
  cors(req, res, () => {
    admin.database().ref('/somePath/someSubPath').once('value')
      .then(snapshot => {
        const value = snapshot.val()
        if (value) return res.status(400).send({ message: 'doSomethingAlreadyCalled' })
        doSomething()
        const updates = { '/somePath/someSubPath': true }
        return admin.database().ref().update(updates)
          .then(() => res.status(200).send({ message: 'OK' }))
      })
      .catch(error => res.status(400).send({ message: 'updateError' }))
  })

})

// HELPERS
const doSomething = () => {
  // needs to be called only once
}

Solution

  • I believe you were downvoted due to the above pseudocode not making complete sense and there being no log or output of what your code is actually doing in your question. Not having a complete picture makes it hard for us to help you.

    Just Going from your structure in the question, your actual code could be calling twice due to function hoisting. Whenever I have this issue, I’ll go back to the api documentation and try to restructure my code from rereading.

    HTH