dalenguyen / firestore-import-export

An application that can help you to backup and restore from Cloud Firestore | Firebase
https://www.npmjs.com/package/firestore-export-import
401 stars 109 forks source link

Better "timestamp" handling #30

Closed dscheffy closed 4 years ago

dscheffy commented 4 years ago

I don't use this package directly, but it helped me a lot when I was building my own import export tool. I recently started adding update timestamps into my firestore data using the FieldValue.serverTimestamp() sentinel. The problem is, when I exported the data and reimported it, the field was no longer a Timestamp object, but rather some unusable json junk... I was able to fix this using some pretty basic replacer/reviver functions in my JSON.parse and JSON.stringify calls:

const replacer = (key, value) => {
    if (typeof value === "object" && value instanceof admin.firestore.Timestamp) {
        return value.toDate().toISOString();
    }
    return value;
}
const isoRegex = /^\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d:[0-5]\d\.\d+Z$/
const reviver = (key: any, value: any) => {
    if(typeof value === 'string' && value.match(isoRegex)) {
        return admin.firestore.Timestamp.fromDate(new Date(value));
    }
    return value;
}

Then you just need to add the second argument to your stringify and parse calls:

// during export
... JSON.stringify(data, replacer) ...
// during import
... JSON.parse(data, reviver) ...

It wouldn't fix timestamps previously exported, but you could always adjust the reviver to account for objects that look like {"_seconds":1223456,"_nanoseconds":38575} -- that seems to be how the default stringify call was serializing the objects.

dalenguyen commented 4 years ago

Thanks @dscheffy, and do check this package out.

https://github.com/dalenguyen/firestore-backup-restore

The time and location is fixed on this.