2017-09-26 13:57:25 +00:00
|
|
|
/**
|
|
|
|
* @flow
|
|
|
|
* DocumentSnapshot representation wrapper
|
|
|
|
*/
|
|
|
|
import DocumentReference from './DocumentReference';
|
2018-01-11 18:28:14 +00:00
|
|
|
import FieldPath from './FieldPath';
|
2017-09-26 13:57:25 +00:00
|
|
|
import Path from './Path';
|
2018-01-11 18:28:14 +00:00
|
|
|
import { isObject } from '../../utils';
|
2017-11-17 14:22:46 +00:00
|
|
|
import { parseNativeMap } from './utils/serialize';
|
2017-11-17 11:07:52 +00:00
|
|
|
|
|
|
|
import type Firestore from './';
|
2017-11-23 17:29:40 +00:00
|
|
|
import type { FirestoreNativeDocumentSnapshot, FirestoreSnapshotMetadata } from '../../types';
|
2017-10-05 09:18:24 +00:00
|
|
|
|
2018-01-11 18:28:14 +00:00
|
|
|
const extractFieldPathData = (data: Object | void, segments: string[]): any => {
|
|
|
|
if (!data || !isObject(data)) {
|
|
|
|
return undefined;
|
|
|
|
}
|
|
|
|
const pathValue = data[segments[0]];
|
|
|
|
if (segments.length === 1) {
|
|
|
|
return pathValue;
|
|
|
|
}
|
|
|
|
return extractFieldPathData(pathValue, segments.slice(1));
|
|
|
|
};
|
|
|
|
|
2017-09-26 13:57:25 +00:00
|
|
|
/**
|
|
|
|
* @class DocumentSnapshot
|
|
|
|
*/
|
|
|
|
export default class DocumentSnapshot {
|
2017-11-17 11:07:52 +00:00
|
|
|
_data: Object | void;
|
2017-11-17 14:22:46 +00:00
|
|
|
_metadata: FirestoreSnapshotMetadata;
|
2017-09-26 13:57:25 +00:00
|
|
|
_ref: DocumentReference;
|
|
|
|
|
2017-11-17 14:22:46 +00:00
|
|
|
constructor(firestore: Firestore, nativeData: FirestoreNativeDocumentSnapshot) {
|
2017-10-10 14:36:08 +00:00
|
|
|
this._data = parseNativeMap(firestore, nativeData.data);
|
2017-10-05 09:18:24 +00:00
|
|
|
this._metadata = nativeData.metadata;
|
2017-09-27 11:57:53 +00:00
|
|
|
this._ref = new DocumentReference(firestore, Path.fromName(nativeData.path));
|
2017-09-26 13:57:25 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
get exists(): boolean {
|
|
|
|
return this._data !== undefined;
|
|
|
|
}
|
|
|
|
|
|
|
|
get id(): string | null {
|
|
|
|
return this._ref.id;
|
|
|
|
}
|
|
|
|
|
2017-11-17 14:22:46 +00:00
|
|
|
get metadata(): FirestoreSnapshotMetadata {
|
2017-10-12 16:22:48 +00:00
|
|
|
return this._metadata;
|
2017-09-26 13:57:25 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
get ref(): DocumentReference {
|
|
|
|
return this._ref;
|
|
|
|
}
|
|
|
|
|
2017-11-17 11:07:52 +00:00
|
|
|
data(): Object | void {
|
2017-09-26 13:57:25 +00:00
|
|
|
return this._data;
|
|
|
|
}
|
|
|
|
|
2018-01-11 18:28:14 +00:00
|
|
|
get(fieldPath: string | FieldPath): any {
|
|
|
|
if (fieldPath instanceof FieldPath) {
|
|
|
|
return extractFieldPathData(this._data, fieldPath._segments);
|
|
|
|
}
|
2017-11-17 11:07:52 +00:00
|
|
|
return this._data ? this._data[fieldPath] : undefined;
|
2017-09-26 13:57:25 +00:00
|
|
|
}
|
|
|
|
}
|