0

When the user opens the app, if auth.currentuser isn't null, then I need to query the user's username. I think a query listener makes sense because I don't want to keep pinging the server every time some code asks for the username. I looked at the Firebase docs they provide this example:

val docRef = db.collection("cities").document("SF")
docRef.addSnapshotListener { snapshot, e ->
    if (e != null) {
        Log.w(TAG, "Listen failed.", e)
        return@addSnapshotListener
    }

    val source = if (snapshot != null && snapshot.metadata.hasPendingWrites())
        "Local"
    else
        "Server"

    if (snapshot != null && snapshot.exists()) {
        Log.d(TAG, "$source data: ${snapshot.data}")
    } else {
        Log.d(TAG, "$source data: null")
    }
}

However, I was advised to try to use as little client side code as possible to optimize security, so the aforementioned example worries me. Is it possible to use a query listener to listen to a server side function that can output the username so that I can still take advantage only running the query once, i.e. saving the username to the client cache?

whatwhatwhat
  • 1,991
  • 4
  • 31
  • 50
  • You should use firestore rules to restrict an access and secure your data. – sdex May 18 '21 at 05:46
  • You can use a get() call and get the data exactly once. That way, you are not listening for changes in real-time. Isn't this what you want? – Alex Mamo May 18 '21 at 06:10
  • @AlexMamo would the `get()` automatically save it to cache? I don't plan on allowing users to change their usernames, so they will only ever need to query it once in their entire account's existence. Trying to find this `get()` in the docs atm... – whatwhatwhat May 19 '21 at 03:46
  • 1
    For Android, Cloud Firestore has offline persistence enables by default. This means, that while the user is offline, the value of the usernames will be read from the cache. However, this doesn't mean that online, will not be read again. I think this article, [How to drastically reduce the number of reads when no documents are changed in Firestore?](https://medium.com/firebase-tips-tricks/how-to-drastically-reduce-the-number-of-reads-when-no-documents-are-changed-in-firestore-8760e2f25e9e) might interest you. – Alex Mamo May 19 '21 at 06:34
  • Hey @whatwhatwhat. Did you make any progress with this? I tried to help with an answer below. Did you see that? Did it make sense? – Frank van Puffelen May 24 '21 at 03:12

1 Answers1

1

Cloud Functions are short-lived, and you pay for the time that they're active. You cannot keep a connection from a Cloud Function open for a long-period of time, like the snapshot listeners that the Firestore server and SDK use.

While it is totally possible to wrap access to Firestore in Cloud Functions, this would follow a more traditional request/response model.

I recommend checking out:

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807