all files / firebase/modules/firestore/ DocumentSnapshot.js

100% Statements 18/18
90% Branches 9/10
100% Functions 8/8
100% Lines 18/18
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69                          10×                           2313× 2313× 2313×             20×                   644×       418×       24×   18×      
/**
 * @flow
 * DocumentSnapshot representation wrapper
 */
import DocumentReference from './DocumentReference';
import FieldPath from './FieldPath';
import Path from './Path';
import { isObject } from '../../utils';
import { parseNativeMap } from './utils/serialize';
 
import type Firestore from './';
import type { NativeDocumentSnapshot, SnapshotMetadata } from './types';
 
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));
};
 
/**
 * @class DocumentSnapshot
 */
export default class DocumentSnapshot {
  _data: Object | void;
  _metadata: SnapshotMetadata;
  _ref: DocumentReference;
 
  constructor(firestore: Firestore, nativeData: NativeDocumentSnapshot) {
    this._data = parseNativeMap(firestore, nativeData.data);
    this._metadata = nativeData.metadata;
    this._ref = new DocumentReference(
      firestore,
      Path.fromName(nativeData.path)
    );
  }
 
  get exists(): boolean {
    return this._data !== undefined;
  }
 
  get id(): string | null {
    return this._ref.id;
  }
 
  get metadata(): SnapshotMetadata {
    return this._metadata;
  }
 
  get ref(): DocumentReference {
    return this._ref;
  }
 
  data(): Object | void {
    return this._data;
  }
 
  get(fieldPath: string | FieldPath): any {
    if (fieldPath instanceof FieldPath) {
      return extractFieldPathData(this._data, fieldPath._segments);
    }
    return this._data ? this._data[fieldPath] : undefined;
  }
}