Gilad
Gilad

Reputation: 663

Firebase - order items according to server time

I want to maintains user comments as an ordered list, based on the server write-time. A couple of questions regarding that:

  1. Can I create (set / push) a locations based on ServerValue.TIMESTAMP?

  2. Can I validate (1) with rules?

  3. Can I safely assume that no two posts will be written at the exact "same moment", overriding eachother?

  4. If I decide to use setWithPriority, and not order by the location-name, can I use ServerValue.TIMESTAMP for the priority (and validate it by rules....)

  5. "Bonus" question - Is there still no way to create a COUNT query in firebase?

=== EDIT ===

I'm trying to achieve a chat-like feature. Messages must be ordered chronologically (by a server-side timestamp) in order to maintain a logical order for "discussion" (if I'll use a client-generated order than one local's machine clock offset could ruin the entire discussion). I can use rules to validate that a ServerValue.TIMESTAMP field is persisted to any new message, however, I can't seem to find a way to make sure that clients actually use setWithPriority() in order to persist data. I can't figure out any way to do this - am i missing something?

Upvotes: 2

Views: 1305

Answers (1)

webduvet
webduvet

Reputation: 4292

  1. you can either .push() which generates auto ID as key or you can .setWithPriority() where your key can be anything and the priority can be pretty much anything as well. As far as I'm aware there is no option to have serverValue.TIMESTAMP as a key. The only way is to retrieve it and explicitly set it as the key with .child(retrievedTime).set(someData)

  2. see 1)

  3. Not sure what you mean exactly since there is no option to set servervalue as a key, but IMHO this is one of the reasons why is it so.

  4. You can use some field on database and set ServerValue.TIMESTAMP and listen for the change - in the callback you will get the most current server time pretty much ASAP as the placeholder is replaced with TIMESTAMP. However there is no guarantee that it is going to be unique. It is perfectly legitimate to have to records with the same priority.

  5. It is promised, but not yet available. You you can do it manually with transactions on every write/delete see docs

Upvotes: 4

Related Questions