Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(firestore): add toJSON() and valueOf() to FirestoreTimestamp #4439

Merged
merged 2 commits into from
Nov 10, 2020
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 22 additions & 0 deletions packages/firestore/lib/FirestoreTimestamp.js
Original file line number Diff line number Diff line change
Expand Up @@ -98,4 +98,26 @@ export default class FirestoreTimestamp {
toString() {
return `FirestoreTimestamp(seconds=${this.seconds}, nanoseconds=${this.nanoseconds})`;
}

toJSON(): { seconds: number, nanoseconds: number } {
return { seconds: this.seconds, nanoseconds: this.nanoseconds };
}

/**
* Converts this object to a primitive string, which allows Timestamp objects to be compared
* using the `>`, `<=`, `>=` and `>` operators.
*/
valueOf(): string {
// This method returns a string of the form <seconds>.<nanoseconds> where <seconds> is
// translated to have a non-negative value and both <seconds> and <nanoseconds> are left-padded
// with zeroes to be a consistent length. Strings with this format then have a lexiographical
// ordering that matches the expected ordering. The <seconds> translation is done to avoid
// having a leading negative sign (i.e. a leading '-' character) in its string representation,
// which would affect its lexiographical ordering.
const adjustedSeconds = this.seconds - MIN_SECONDS;
// Note: Up to 12 decimal digits are required to represent all valid 'seconds' values.
const formattedSeconds = String(adjustedSeconds).padStart(12, '0');
const formattedNanoseconds = String(this.nanoseconds).padStart(9, '0');
return formattedSeconds + '.' + formattedNanoseconds;
}
}