简体   繁体   中英

Server timestamp using firebase

I am working on a review/comment process and would like to be able to store each review/comment given by a user for another one in firebase, with each review/rating given at the same time being under the same timestamp. I was using the JS function new Date().getTime() initially, and this works fine, but to ensure that users can't tamper with the value (ie by changing the date on their computer) I would like to use firebase timestamp instead.

Now, I want the end product to be a map:

[chatStartTime] : {
   review : stars,
   time : chatStartTime
 }

Which I then incorporate into a firebase document using transaction.set(). Now the issue is the ChatStartTime, which is supposed to represent this timestamp. I have the code:

var chatStartTime = firebase.firestore.FieldValue.serverTimestamp();

As an aside, I am also hoping to get:

var chatStartTimeDate = chatStartTime.toDate();

However chatStartTimeDate leads to an error – my understanding is that this is because chatStartTime is essentially "void" until it is added to a document; is there any way to get around this and use this function? Also, if I just use chatStartTime for both instances, I end up with a map on the database of the form:

[object Object] 
  review : 4.5
  time :
        .sv: "timestamp"

Where .sv is a string type. How can I solve this issue? I'd like the end result to look something like (for example)

 1579194722735
  review : 4.5
  time : 1579194722735

The FieldValue.serverTimestamp() value is written on the server at time of write. So you can't get it before the write happens. However, you can get the writeTime from the response. This should give you what you're after. Alternately, you could read the document back out after you write it to fetch the timestamp (but that seems unnecessary).

myCollection
    .doc('foo')
    .create({ timestamp: FirebaseFirestore.FieldValue.serverTimestamp() })
    .then(result => {
      const serverTime: Date = result.writeTime.toDate();
    });

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