2017-09-26 14:57:25 +01:00
|
|
|
/**
|
|
|
|
* @flow
|
|
|
|
* DocumentSnapshot representation wrapper
|
|
|
|
*/
|
|
|
|
import DocumentReference from './DocumentReference';
|
2018-01-11 18:28:14 +00:00
|
|
|
import FieldPath from './FieldPath';
|
2017-09-26 14:57:25 +01:00
|
|
|
import Path from './Path';
|
2018-04-12 12:30:41 +01:00
|
|
|
import { isObject, deepGet } 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 './';
|
2018-02-14 13:00:19 +00:00
|
|
|
import type { NativeDocumentSnapshot, SnapshotMetadata } from './types';
|
2017-10-05 10:18:24 +01: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 14:57:25 +01:00
|
|
|
/**
|
|
|
|
* @class DocumentSnapshot
|
|
|
|
*/
|
|
|
|
export default class DocumentSnapshot {
|
2017-11-17 11:07:52 +00:00
|
|
|
_data: Object | void;
|
2018-02-14 13:00:19 +00:00
|
|
|
_metadata: SnapshotMetadata;
|
2017-09-26 14:57:25 +01:00
|
|
|
_ref: DocumentReference;
|
|
|
|
|
2018-02-14 13:00:19 +00:00
|
|
|
constructor(firestore: Firestore, nativeData: NativeDocumentSnapshot) {
|
2017-10-10 15:36:08 +01:00
|
|
|
this._data = parseNativeMap(firestore, nativeData.data);
|
2017-10-05 10:18:24 +01:00
|
|
|
this._metadata = nativeData.metadata;
|
2018-01-25 18:25:39 +00:00
|
|
|
this._ref = new DocumentReference(
|
|
|
|
firestore,
|
|
|
|
Path.fromName(nativeData.path)
|
|
|
|
);
|
2017-09-26 14:57:25 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
get exists(): boolean {
|
|
|
|
return this._data !== undefined;
|
|
|
|
}
|
|
|
|
|
|
|
|
get id(): string | null {
|
|
|
|
return this._ref.id;
|
|
|
|
}
|
|
|
|
|
2018-02-14 13:00:19 +00:00
|
|
|
get metadata(): SnapshotMetadata {
|
2017-10-12 18:22:48 +02:00
|
|
|
return this._metadata;
|
2017-09-26 14:57:25 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
get ref(): DocumentReference {
|
|
|
|
return this._ref;
|
|
|
|
}
|
|
|
|
|
2018-04-13 11:50:30 +01:00
|
|
|
data = (): Object | void => this._data;
|
2017-09-26 14:57:25 +01:00
|
|
|
|
2018-04-13 11:50:30 +01:00
|
|
|
get = (fieldPath: string | FieldPath): any => {
|
2018-01-11 18:28:14 +00:00
|
|
|
if (fieldPath instanceof FieldPath) {
|
|
|
|
return extractFieldPathData(this._data, fieldPath._segments);
|
|
|
|
}
|
2018-04-12 12:38:28 +01:00
|
|
|
|
|
|
|
return deepGet(this._data, fieldPath, '.');
|
2018-04-13 11:50:30 +01:00
|
|
|
};
|
2017-09-26 14:57:25 +01:00
|
|
|
}
|