1

i am using firebase database REST api to post data. The structure is

orders: {
"milk" : 10,
"cream" : 13
}

My use case is to increment the quantities by 1 to look them as:

orders: {
    "milk" : 11,
    "cream" : 14
    }

In general, I see two REST calls:

  1. make a GET call to get the current numbers in my client
  2. make a PUT call with updated number

is there a way to do that as a single call to increment current values?

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
Vik
  • 8,721
  • 27
  • 83
  • 168

2 Answers2

2

If you're using one of the Firebase SDKs, this would be accomplished with a transaction (web).

There currently is no equivalent in the REST API, that would allow you to do this in one go.

What you could consider is using security rules to ensure that only valid transitions are allowed. But this easily gets quite tricky, as you can see in my answer here: https://stackoverflow.com/a/37956590.

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

If you need an HTTP endpoint that can atomically get and set a value in your Realtime Database, you could use Cloud Functions for Firebase to create an HTTPS trigger that uses the Admin SDK to perform the transaction and outputs the updated count back to the caller.

Doug Stevenson
  • 297,357
  • 32
  • 422
  • 441
  • i dont need the updated counter but just need to get the counter first and then update it – Vik Jul 24 '17 at 20:32
  • You can code your function any way you like. If you don't want to return the updated value, there's no need to write it that way. – Doug Stevenson Jul 24 '17 at 20:49
  • This is perfectly valid! Why the downvote? You could listen to any Firebase event and then update the counter with Functions. By example, you could make another node "user_orders": { "jwdbawodn" {"item":"milk", "UID": "dawdawd", "timestamp": 131233412 } }. This way any user can create an increase by adding a new order when a new order is created, you can list to it and increase it using Functions. This has the additional benefit that you get a quick list of the recent user activity. – cutiko Jul 24 '17 at 20:50