Skip to content

Commit 0647a82

Browse files
authored
Handle Firestore timestamp values with varying degrees of precision (#123)
1 parent 3cf0421 commit 0647a82

File tree

2 files changed

+20
-12
lines changed

2 files changed

+20
-12
lines changed

spec/providers/firestore.spec.ts

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -295,7 +295,7 @@ describe('Firestore Functions', () => {
295295
expect(snapshot.data()['referenceVal'].path).to.equal('doc1/id');
296296
});
297297

298-
it('should parse timestamp values', () => {
298+
it('should parse timestamp values with precision to the millisecond', () => {
299299
let raw = constructValue({
300300
'timestampVal': {
301301
'timestampValue': '2017-06-13T00:58:40.349Z',
@@ -307,6 +307,19 @@ describe('Firestore Functions', () => {
307307
expect(snapshot.data()).to.deep.equal({'timestampVal': new Date('2017-06-13T00:58:40.349Z')});
308308
});
309309

310+
it('should parse timestamp values with precision to the second', () => {
311+
let raw = constructValue({
312+
'timestampVal': {
313+
'timestampValue': '2017-06-13T00:58:40Z',
314+
},
315+
});
316+
let snapshot = firestore.dataConstructor({
317+
data: { value: raw },
318+
});
319+
expect(snapshot.data()).to.deep.equal({'timestampVal': new Date('2017-06-13T00:58:40Z')});
320+
321+
});
322+
310323
it('should parse binary values', () => {
311324
// Format defined in https://developers.google.com/discovery/v1/type-format
312325
let raw = constructValue({

src/encoder.ts

Lines changed: 6 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -26,16 +26,11 @@ export function dateToTimestampProto(timeString) {
2626
}
2727
let date = new Date(timeString);
2828
let seconds = Math.floor(date.getTime() / 1000);
29-
let nanoString = timeString.substring(20, timeString.length - 1);
30-
31-
if (nanoString.length === 3) {
32-
nanoString = `${nanoString}000000`;
33-
} else if (nanoString.length === 6) {
34-
nanoString = `${nanoString}000`;
29+
let nanos = 0;
30+
if (timeString.length > 20) {
31+
const nanoString = timeString.substring(20, timeString.length - 1);
32+
const trailingZeroes = 9 - nanoString.length;
33+
nanos = parseInt(nanoString, 10) * Math.pow(10, trailingZeroes);
3534
}
36-
let proto = {
37-
seconds: seconds,
38-
nanos: parseInt(nanoString, 10),
39-
};
40-
return proto;
35+
return { seconds, nanos };
4136
};

0 commit comments

Comments
 (0)