1
votes

In typescript, I can create document with field like createdAt, updatedAt as Timestamp by using change.after.updateTime or snap.createTime inside Cloud Functions Triggers.

But inside other triggers like onUpdate, the field change.after.data().updatedAt that suppose to store a Timestamp, gives me an object.

How can i compare them if i can't get them as Timestamp value ? How can i get the field as Timestamp value ? Thanks

admin.initializeApp();
const firestore = admin.firestore();
const settings = { timestampsInSnapshots: true };
firestore.settings(settings);


export const setCreatedAt = functions.firestore.document('path')
    .onCreate(async (snap, context) => {

        return snap.ref.update({
            createdAt: snap.createTime, // Type Timestamp
            updatedAt: snap.createTime // Type Timestamp
        });

    });

export const setUpdatedAt = functions.firestore.document('path')
    .onUpdate(async (change, context) => {

        let beforeTimestamp = change.before.data().updatedAt; // Type object, not Timestamp
        let afterTimestamp = change.after.data().updatedAt; // Type object, not Timestamp

        console.log('beforeTimestamp', beforeTimestamp);
        console.log('afterTimestamp', afterTimestamp);

        if (change.before.data().updatedAt === change.after.data().updatedAt) {
            change.after.ref.update({
                updatedAt: change.after.updateTime, // Type Timestamp
            });
        }
    });

The image below shows the logs when doing an update. Example

It looks like the { timestampsInSnapshots: true } settings has no effect because i still have the warning inside the console. But why ?

The behavior for Date objects stored in Firestore is going to change AND YOUR APP MAY BREAK

1
Note that after v0.20.0, the googleapis/nodejs-firestore timestampsInSnapshots setting defaults to true. So you don't need to explicitly set this anymore. - augustzf

1 Answers

0
votes

You need to convert the returned Timestamp objects to Date objects:

beforeTimestamp.toDate()

Then you can compare the Date objects with < and > operators. If you need to compare for equality, then you'll need to convert the dates to numbers first: beforeTimestamp.toDate().getTime()