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: add support for Typescript Custom Mapping #828

Merged
merged 21 commits into from Jan 14, 2020
Merged
Show file tree
Hide file tree
Changes from 11 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
10 changes: 6 additions & 4 deletions dev/src/document-change.ts
Expand Up @@ -15,6 +15,8 @@
*/

import {QueryDocumentSnapshot} from './document';
import {DocumentData, FirestoreDataConverter} from './types';
import {defaultConverter} from './watch';

export type DocumentChangeType = 'added' | 'removed' | 'modified';

Expand All @@ -24,9 +26,9 @@ export type DocumentChangeType = 'added' | 'removed' | 'modified';
*
* @class
*/
export class DocumentChange {
export class DocumentChange<T = DocumentData> {
private readonly _type: DocumentChangeType;
private readonly _document: QueryDocumentSnapshot;
private readonly _document: QueryDocumentSnapshot<T>;
private readonly _oldIndex: number;
private readonly _newIndex: number;

Expand All @@ -42,7 +44,7 @@ export class DocumentChange {
*/
constructor(
type: DocumentChangeType,
document: QueryDocumentSnapshot,
document: QueryDocumentSnapshot<T>,
oldIndex: number,
newIndex: number
) {
Expand Down Expand Up @@ -169,7 +171,7 @@ export class DocumentChange {
* @param {*} other The value to compare against.
* @return true if this `DocumentChange` is equal to the provided value.
*/
isEqual(other: DocumentChange): boolean {
isEqual(other: DocumentChange<T>): boolean {
if (this === other) {
return true;
}
Expand Down
85 changes: 51 additions & 34 deletions dev/src/document.ts
Expand Up @@ -36,9 +36,9 @@ import api = google.firestore.v1;
*
* @private
*/
export class DocumentSnapshotBuilder {
export class DocumentSnapshotBuilder<T = DocumentData> {
/** The reference to the document. */
ref?: DocumentReference;
ref: DocumentReference<T>;

/** The fields of the Firestore `Document` Protobuf backing this document. */
fieldsProto?: ApiMapValue;
Expand All @@ -52,14 +52,22 @@ export class DocumentSnapshotBuilder {
/** The time when this document was last updated. */
updateTime?: Timestamp;

/**
thebrianchen marked this conversation as resolved.
Show resolved Hide resolved
* We include the DocumentReference in the constructor in order to allow the
* DocumentSnapshotBuilder to be typed with <T> when it is constructed.
*/
constructor(ref: DocumentReference<T>) {
thebrianchen marked this conversation as resolved.
Show resolved Hide resolved
this.ref = ref;
}

/**
* Builds the DocumentSnapshot.
*
* @private
* @returns Returns either a QueryDocumentSnapshot (if `fieldsProto` was
* provided) or a DocumentSnapshot.
*/
build(): QueryDocumentSnapshot | DocumentSnapshot {
build(): QueryDocumentSnapshot<T> | DocumentSnapshot<T> {
assert(
(this.fieldsProto !== undefined) === (this.createTime !== undefined),
'Create time should be set iff document exists.'
Expand Down Expand Up @@ -94,8 +102,8 @@ export class DocumentSnapshotBuilder {
*
* @class
*/
export class DocumentSnapshot {
private _ref: DocumentReference;
export class DocumentSnapshot<T = DocumentData> {
private _ref: DocumentReference<T>;
private _fieldsProto: ApiMapValue | undefined;
private _serializer: Serializer;
private _readTime: Timestamp | undefined;
Expand All @@ -116,7 +124,7 @@ export class DocumentSnapshot {
* if the document does not exist).
*/
constructor(
ref: DocumentReference,
ref: DocumentReference<T>,
fieldsProto?: ApiMapValue,
thebrianchen marked this conversation as resolved.
Show resolved Hide resolved
readTime?: Timestamp,
createTime?: Timestamp,
Expand All @@ -138,10 +146,10 @@ export class DocumentSnapshot {
* @param obj The object to store in the DocumentSnapshot.
* @return The created DocumentSnapshot.
*/
static fromObject(
ref: DocumentReference,
static fromObject<U>(
ref: DocumentReference<U>,
obj: DocumentData
): DocumentSnapshot {
): DocumentSnapshot<U> {
const serializer = ref.firestore._serializer!;
return new DocumentSnapshot(ref, serializer.encodeFields(obj));
}
Expand All @@ -156,10 +164,10 @@ export class DocumentSnapshot {
* @param data The field/value map to expand.
* @return The created DocumentSnapshot.
*/
static fromUpdateMap(
ref: DocumentReference,
static fromUpdateMap<U>(
ref: DocumentReference<U>,
data: UpdateMap
): DocumentSnapshot {
): DocumentSnapshot<U> {
const serializer = ref.firestore._serializer!;

/**
Expand Down Expand Up @@ -270,7 +278,7 @@ export class DocumentSnapshot {
* }
* });
*/
get ref(): DocumentReference {
get ref(): DocumentReference<T> {
return this._ref;
}

Expand Down Expand Up @@ -364,8 +372,8 @@ export class DocumentSnapshot {
* Retrieves all fields in the document as an object. Returns 'undefined' if
* the document doesn't exist.
*
* @returns {DocumentData|undefined} An object containing all fields in the
* document or 'undefined' if the document doesn't exist.
* @returns {T|undefined} An object containing all fields in the document or
* 'undefined' if the document doesn't exist.
*
* @example
* let documentRef = firestore.doc('col/doc');
Expand All @@ -375,11 +383,7 @@ export class DocumentSnapshot {
* console.log(`Retrieved data: ${JSON.stringify(data)}`);
* });
*/
// We deliberately use `any` in the external API to not impose type-checking
// on end users.
// tslint:disable-next-line no-any
data(): {[field: string]: any} | undefined {
// tslint:disable-line no-any
data(): T | undefined {
const fields = this._fieldsProto;

if (fields === undefined) {
Expand All @@ -390,7 +394,7 @@ export class DocumentSnapshot {
for (const prop of Object.keys(fields)) {
obj[prop] = this._serializer.decodeValue(fields[prop]);
}
return obj;
return this.ref._converter.fromFirestore(obj);
}

/**
Expand Down Expand Up @@ -467,6 +471,17 @@ export class DocumentSnapshot {
return this._fieldsProto === undefined || isEmpty(this._fieldsProto);
}

/**
* Returns the original field proto of the DocumentSnapshot. This is used
* when reconstructing the DocumentSnapshot with a DocumentSnapshotBuilder.
*
* @private
* @return {ApiMapValue | undefined}
*/
get fieldsProto(): ApiMapValue | undefined {
return this._fieldsProto;
}

/**
* Convert a document snapshot to the Firestore 'Document' Protobuf.
*
Expand All @@ -490,7 +505,7 @@ export class DocumentSnapshot {
* @return {boolean} true if this `DocumentSnapshot` is equal to the provided
* value.
*/
isEqual(other: DocumentSnapshot): boolean {
isEqual(other: DocumentSnapshot<T>): boolean {
// Since the read time is different on every document read, we explicitly
// ignore all document metadata in this comparison.
return (
Expand All @@ -517,7 +532,9 @@ export class DocumentSnapshot {
* @class
* @extends DocumentSnapshot
*/
export class QueryDocumentSnapshot extends DocumentSnapshot {
export class QueryDocumentSnapshot<T = DocumentData> extends DocumentSnapshot<
T
> {
/**
* @hideconstructor
*
Expand All @@ -529,7 +546,7 @@ export class QueryDocumentSnapshot extends DocumentSnapshot {
* @param updateTime The time when the document was last updated.
*/
constructor(
ref: DocumentReference,
ref: DocumentReference<T>,
fieldsProto: ApiMapValue,
readTime: Timestamp,
createTime: Timestamp,
Expand Down Expand Up @@ -582,7 +599,7 @@ export class QueryDocumentSnapshot extends DocumentSnapshot {
*
* @override
*
* @returns {DocumentData} An object containing all fields in the document.
* @returns {T} An object containing all fields in the document.
*
* @example
* let query = firestore.collection('col');
Expand All @@ -592,7 +609,7 @@ export class QueryDocumentSnapshot extends DocumentSnapshot {
* console.log(`Retrieved data: ${JSON.stringify(data)}`);
* });
*/
data(): DocumentData {
data(): T {
const data = super.data();
if (!data) {
throw new Error(
Expand Down Expand Up @@ -871,7 +888,7 @@ export class DocumentMask {
* @private
* @class
*/
export class DocumentTransform {
export class DocumentTransform<T = DocumentData> {
/**
* @private
* @hideconstructor
Expand All @@ -880,7 +897,7 @@ export class DocumentTransform {
* @param transforms A Map of FieldPaths to FieldTransforms.
*/
constructor(
private readonly ref: DocumentReference,
private readonly ref: DocumentReference<T>,
private readonly transforms: Map<FieldPath, FieldTransform>
) {}

Expand All @@ -892,10 +909,10 @@ export class DocumentTransform {
* @param obj The object to extract the transformations from.
* @returns The Document Transform.
*/
static fromObject(
ref: DocumentReference,
static fromObject<T>(
ref: DocumentReference<T>,
obj: DocumentData
): DocumentTransform {
): DocumentTransform<T> {
const updateMap = new Map<FieldPath, unknown>();

for (const prop of Object.keys(obj)) {
Expand All @@ -913,10 +930,10 @@ export class DocumentTransform {
* @param data The update data to extract the transformations from.
* @returns The Document Transform.
*/
static fromUpdateMap(
ref: DocumentReference,
static fromUpdateMap<T>(
ref: DocumentReference<T>,
data: UpdateMap
): DocumentTransform {
): DocumentTransform<T> {
const transforms = new Map<FieldPath, FieldTransform>();

function encode_(val: unknown, path: FieldPath, allowTransforms: boolean) {
Expand Down