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 15 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
9 changes: 5 additions & 4 deletions dev/src/document-change.ts
Expand Up @@ -15,6 +15,7 @@
*/

import {QueryDocumentSnapshot} from './document';
import {DocumentData} from './types';

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

Expand All @@ -24,9 +25,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 +43,7 @@ export class DocumentChange {
*/
constructor(
type: DocumentChangeType,
document: QueryDocumentSnapshot,
document: QueryDocumentSnapshot<T>,
oldIndex: number,
newIndex: number
) {
Expand Down Expand Up @@ -169,7 +170,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
89 changes: 44 additions & 45 deletions dev/src/document.ts
Expand Up @@ -36,10 +36,7 @@ import api = google.firestore.v1;
*
* @private
*/
export class DocumentSnapshotBuilder {
/** The reference to the document. */
ref?: DocumentReference;

export class DocumentSnapshotBuilder<T = DocumentData> {
/** The fields of the Firestore `Document` Protobuf backing this document. */
fieldsProto?: ApiMapValue;

Expand All @@ -52,14 +49,20 @@ 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(readonly ref: DocumentReference<T>) {}

/**
* 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,9 +97,8 @@ export class DocumentSnapshotBuilder {
*
* @class
*/
export class DocumentSnapshot {
private _ref: DocumentReference;
private _fieldsProto: ApiMapValue | undefined;
export class DocumentSnapshot<T = DocumentData> {
private _ref: DocumentReference<T>;
private _serializer: Serializer;
private _readTime: Timestamp | undefined;
private _createTime: Timestamp | undefined;
Expand All @@ -116,14 +118,13 @@ export class DocumentSnapshot {
* if the document does not exist).
*/
constructor(
ref: DocumentReference,
fieldsProto?: ApiMapValue,
ref: DocumentReference<T>,
readonly fieldsProto?: ApiMapValue,
Copy link
Contributor

Choose a reason for hiding this comment

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

I am undecided whether this should be fieldsProto or _ fieldsProto. This is a public field for internal consumption.

Copy link
Author

Choose a reason for hiding this comment

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

I've renamed to _fieldsProto so that external developers know that it's not intended for external consumption.

readTime?: Timestamp,
createTime?: Timestamp,
updateTime?: Timestamp
) {
this._ref = ref;
this._fieldsProto = fieldsProto;
this._serializer = ref.firestore._serializer!;
this._readTime = readTime;
this._createTime = createTime;
Expand All @@ -138,10 +139,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 +157,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 @@ -250,7 +251,7 @@ export class DocumentSnapshot {
* });
*/
get exists(): boolean {
return this._fieldsProto !== undefined;
return this.fieldsProto !== undefined;
}

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

Expand Down Expand Up @@ -364,8 +365,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,12 +376,8 @@ 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
const fields = this._fieldsProto;
data(): T | undefined {
const fields = this.fieldsProto;

if (fields === undefined) {
return undefined;
Expand All @@ -390,7 +387,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 @@ -437,7 +434,7 @@ export class DocumentSnapshot {
* undefined if no such field exists.
*/
protoField(field: string | FieldPath): api.IValue | undefined {
let fields: ApiMapValue | api.IValue | undefined = this._fieldsProto;
let fields: ApiMapValue | api.IValue | undefined = this.fieldsProto;

if (fields === undefined) {
return undefined;
Expand All @@ -464,7 +461,7 @@ export class DocumentSnapshot {
* @return {boolean}
*/
get isEmpty(): boolean {
return this._fieldsProto === undefined || isEmpty(this._fieldsProto);
return this.fieldsProto === undefined || isEmpty(this.fieldsProto);
}

/**
Expand All @@ -477,7 +474,7 @@ export class DocumentSnapshot {
return {
update: {
name: this._ref.formattedName,
fields: this._fieldsProto,
fields: this.fieldsProto,
},
};
}
Expand All @@ -490,14 +487,14 @@ 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 (
this === other ||
(other instanceof DocumentSnapshot &&
this._ref.isEqual(other._ref) &&
deepEqual(this._fieldsProto, other._fieldsProto, {strict: true}))
deepEqual(this.fieldsProto, other.fieldsProto, {strict: true}))
);
}
}
Expand All @@ -517,7 +514,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 +528,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 +581,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 +591,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 +870,7 @@ export class DocumentMask {
* @private
* @class
*/
export class DocumentTransform {
export class DocumentTransform<T = DocumentData> {
/**
* @private
* @hideconstructor
Expand All @@ -880,7 +879,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 +891,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 +912,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