Conchi Bermejo
Conchi Bermejo

Reputation: 353

Firestore serverTimestamp + 24 hours

I am implementing a scheduled cloud function that deletes expired documents.

What I am doing in the GCF to upload content with a TTL of 24 hours is:

  1. Get the server timestamp
  2. Calculate the "expiresAt" date (something like new Date().addHours(24))

Is the right way to get "expiresAt" using the serverTimestamp like this in a google cloud function?

 Date.prototype.addHours = function(hours) {
     this.setTime(this.getHours() + hours);
     return this;
 } 

 ...

 const date = admin.firestore.FieldValue.serverTimestamp();
 const expiresAt = date.toDate().addHours(24);

Also, if expiresAt is a Date object, will it be automatically converted to a Firestore timestamp when storing it?

Thank you very much.

Upvotes: 0

Views: 1670

Answers (1)

Doug Stevenson
Doug Stevenson

Reputation: 317948

You can't really "get" a Firestore server timestamp. admin.firestore.FieldValue.serverTimestamp() return a static token value object, not a date. Those tokens are evaluated on the Firestore server at the time a write happens.

Since you are already running code on a Google backend in Cloud Functions, you can just use the current time as reckoned by JavaScript. It will be the same as the current time in Firestore, but you can do math on it.

const now = Date.now()
const expiresAt = new Date(now + 24*60*60*1000)

Upvotes: 3

Related Questions