Skip to content

Add toJSON() support for Firestore classes #4298

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

Merged
merged 6 commits into from
Jan 26, 2021
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
8 changes: 8 additions & 0 deletions .changeset/clean-meals-double.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
---
'@firebase/app-compat': patch
'@firebase/app': patch
'@firebase/app-types': patch
'@firebase/firestore': patch
---

Firestore classes like DocumentReference and Query can now be serialized to JSON (#4258)
8 changes: 8 additions & 0 deletions packages-exp/app-compat/src/firebaseApp.ts
Original file line number Diff line number Diff line change
Expand Up @@ -134,6 +134,14 @@ export class FirebaseAppImpl implements FirebaseApp {
_addOrOverwriteComponent(component: Component): void {
_addOrOverwriteComponent(this.app, component);
}

toJSON(): object {
return {
name: this.name,
automaticDataCollectionEnabled: this.automaticDataCollectionEnabled,
options: this.options
};
}
}

// TODO: investigate why the following needs to be commented out
Expand Down
2 changes: 2 additions & 0 deletions packages/app-types/index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -112,6 +112,8 @@ export interface FirebaseNamespace {
// Sets log handler for all Firebase components.
onLog(logCallback: LogCallback, options?: LogOptions): void;

toJSON(): object;
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You should also modify the Firestore and the Firebase types if you modify this (firestore-types/index.d.ts and firebase/index.d.ts)

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

done.


// The current SDK version.
SDK_VERSION: string;
}
Expand Down
8 changes: 8 additions & 0 deletions packages/app/src/firebaseApp.ts
Original file line number Diff line number Diff line change
Expand Up @@ -163,6 +163,14 @@ export class FirebaseAppImpl implements FirebaseApp {
this.container.addOrOverwriteComponent(component);
}

toJSON(): object {
return {
name: this.name,
automaticDataCollectionEnabled: this.automaticDataCollectionEnabled,
options: this.options
};
}

/**
* This function will throw an Error if the App has already been deleted -
* use before performing API actions on the App.
Expand Down
15 changes: 12 additions & 3 deletions packages/firestore/src/remote/backoff.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,12 +24,12 @@ const LOG_TAG = 'ExponentialBackoff';
* Initial backoff time in milliseconds after an error.
* Set to 1s according to https://cloud.google.com/apis/design/errors.
*/
const DEFAULT_BACKOFF_INITIAL_DELAY_MS = 1000;
export const DEFAULT_BACKOFF_INITIAL_DELAY_MS = 1000;

const DEFAULT_BACKOFF_FACTOR = 1.5;
export const DEFAULT_BACKOFF_FACTOR = 1.5;

/** Maximum backoff time in milliseconds */
const DEFAULT_BACKOFF_MAX_DELAY_MS = 60 * 1000;
export const DEFAULT_BACKOFF_MAX_DELAY_MS = 60 * 1000;

/**
* A helper for running delayed tasks following an exponential backoff curve
Expand Down Expand Up @@ -163,6 +163,15 @@ export class ExponentialBackoff {
}
}

toJSON(): object {
return {
timerId: this.timerId,
initialDelayMs: this.initialDelayMs,
backoffFactor: this.backoffFactor,
maxDelayMs: this.maxDelayMs
};
}

/** Returns a random value in the range [-currentBaseMs/2, currentBaseMs/2] */
private jitterDelayMs(): number {
return (Math.random() - 0.5) * this.currentBaseMs;
Expand Down
9 changes: 9 additions & 0 deletions packages/firestore/src/util/async_queue_impl.ts
Original file line number Diff line number Diff line change
Expand Up @@ -295,6 +295,15 @@ export class AsyncQueueImpl implements AsyncQueue {
debugAssert(index >= 0, 'Delayed operation not found.');
this.delayedOperations.splice(index, 1);
}

toJSON(): object {
return {
retryableOperationsCount: this.retryableOps.length,
delayedOperationsCount: this.delayedOperations.length,
operationsInProgress: this.operationInProgress,
backoff: this.backoff
};
}
}

export function newAsyncQueue(): AsyncQueue {
Expand Down
25 changes: 25 additions & 0 deletions packages/firestore/test/unit/api/database.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,10 @@ describe('CollectionReference', () => {
expectEqual(collectionReference('foo'), collectionReference('foo'));
expectNotEqual(collectionReference('foo'), collectionReference('bar'));
});

it('JSON.stringify() does not throw', () => {
JSON.stringify(collectionReference('foo'));
});
});

describe('DocumentReference', () => {
Expand All @@ -42,6 +46,10 @@ describe('DocumentReference', () => {
documentReference('rooms/bar')
);
});

it('JSON.stringify() does not throw', () => {
JSON.stringify(documentReference('foo/bar'));
});
});

describe('DocumentSnapshot', () => {
Expand Down Expand Up @@ -72,13 +80,24 @@ describe('DocumentSnapshot', () => {
documentSnapshot('rooms/bar', { a: 1 }, false)
);
});

it('JSON.stringify() does not throw', () => {
JSON.stringify(documentSnapshot('foo/bar', { a: 1 }, true));
JSON.stringify(documentSnapshot('foo/bar', { a: 1 }, false));
JSON.stringify(documentSnapshot('foo/bar', null, true));
JSON.stringify(documentSnapshot('foo/bar', null, false));
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Do these four cases test different paths in a toJSON call?

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not anymore, removed.

});
});

describe('Query', () => {
it('support equality checking with isEqual()', () => {
expectEqual(query('foo'), query('foo'));
expectNotEqual(query('foo'), query('bar'));
});

it('JSON.stringify() does not throw', () => {
JSON.stringify(query('foo'));
});
});

describe('QuerySnapshot', () => {
Expand Down Expand Up @@ -123,6 +142,12 @@ describe('QuerySnapshot', () => {
querySnapshot('foo', {}, { a: { a: 1 } }, keys('foo/a'), false, true)
);
});

it('JSON.stringify() does not throw', () => {
JSON.stringify(
querySnapshot('foo', {}, { a: { a: 1 } }, keys(), false, false)
);
});
});

describe('SnapshotMetadata', () => {
Expand Down
26 changes: 26 additions & 0 deletions packages/firestore/test/unit/util/async_queue.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,11 @@ import { expect, use } from 'chai';
import * as chaiAsPromised from 'chai-as-promised';

import { IndexedDbTransactionError } from '../../../src/local/simple_db';
import {
DEFAULT_BACKOFF_FACTOR,
DEFAULT_BACKOFF_INITIAL_DELAY_MS,
DEFAULT_BACKOFF_MAX_DELAY_MS
} from '../../../src/remote/backoff';
import { fail } from '../../../src/util/assert';
import { TimerId } from '../../../src/util/async_queue';
import {
Expand Down Expand Up @@ -417,6 +422,27 @@ describe('AsyncQueue', () => {
await queue.drain();
expect(completedSteps).to.deep.equal([1, 2, 4]);
});

it('serializes to JSON', async () => {
const queue = newAsyncQueue() as AsyncQueueImpl;
// eslint-disable-next-line @typescript-eslint/no-floating-promises
queue.enqueueAfterDelay(timerId1, 20000, () => Promise.resolve());
// toJSON() does not recursively call itself when serializing elements.
// We use JSON.stringify() here in order to check that `backoff` is
// serialized properly.
expect(JSON.parse(JSON.stringify(queue.toJSON()))).to.deep.equal({
delayedOperationsCount: 1,
operationsInProgress: false,
retryableOperationsCount: 0,
backoff: {
timerId: TimerId.AsyncQueueRetry,
initialDelayMs: DEFAULT_BACKOFF_INITIAL_DELAY_MS,
backoffFactor: DEFAULT_BACKOFF_FACTOR,
maxDelayMs: DEFAULT_BACKOFF_MAX_DELAY_MS
}
});
await queue.drain();
});
});

function defer<T>(op: () => T): Promise<T> {
Expand Down