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

62.07% Statements 18/29
33.33% Branches 4/12
100% Functions 7/7
62.07% Lines 18/29
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 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182                                                                                                                                                                                                                                                                                                                                       
/**
 * @flow
 * Firestore Transaction representation wrapper
 */
import { mergeFieldPathData } from './utils';
import { buildNativeMap } from './utils/serialize';
 
import type Firestore from './';
import type { TransactionMeta } from './TransactionHandler';
import type DocumentReference from './DocumentReference';
import DocumentSnapshot from './DocumentSnapshot';
import { isObject, isString } from '../../utils';
import FieldPath from './FieldPath';
import { getNativeModule } from '../../utils/native';
 
type Command = {
  type: 'set' | 'update' | 'delete',
  path: string,
  data?: { [string]: any },
  options?: SetOptions | {},
};
 
type SetOptions = {
  merge: boolean,
};
 
// TODO docs state all get requests must be made FIRST before any modifications
// TODO so need to validate that
 
/**
 * @class Transaction
 */
export default class Transaction {
  _pendingResult: ?any;
  _firestore: Firestore;
  _meta: TransactionMeta;
  _commandBuffer: Array<Command>;
 
  constructor(firestore: Firestore, meta: TransactionMeta) {
    this._meta = meta;
    this._commandBuffer = [];
    this._firestore = firestore;
    this._pendingResult = undefined;
  }
 
  /**
   * -------------
   * INTERNAL API
   * -------------
   */
 
  /**
   * Clears the command buffer and any pending result in prep for
   * the next transaction iteration attempt.
   *
   * @private
   */
  _prepare() {
    this._commandBuffer = [];
    this._pendingResult = undefined;
  }
 
  /**
   * -------------
   *  PUBLIC API
   * -------------
   */
 
  /**
   * Reads the document referenced by the provided DocumentReference.
   *
   * @param documentRef DocumentReference A reference to the document to be retrieved. Value must not be null.
   *
   * @returns Promise<DocumentSnapshot>
   */
  get(documentRef: DocumentReference): Promise<DocumentSnapshot> {
    // todo validate doc ref
    return getNativeModule(this._firestore)
      .transactionGetDocument(this._meta.id, documentRef.path)
      .then(result => new DocumentSnapshot(this._firestore, result));
  }
 
  /**
   * Writes to the document referred to by the provided DocumentReference.
   * If the document does not exist yet, it will be created. If you pass options,
   * the provided data can be merged into the existing document.
   *
   * @param documentRef DocumentReference A reference to the document to be created. Value must not be null.
   * @param data Object An object of the fields and values for the document.
   * @param options SetOptions An object to configure the set behavior.
   *        Pass {merge: true} to only replace the values specified in the data argument.
   *        Fields omitted will remain untouched.
   *
   * @returns {Transaction}
   */
  set(
    documentRef: DocumentReference,
    data: Object,
    options?: SetOptions
  ): Transaction {
    // todo validate doc ref
    // todo validate data is object
    this._commandBuffer.push({
      type: 'set',
      path: documentRef.path,
      data: buildNativeMap(data),
      options: options || {},
    });
 
    return this;
  }
 
  /**
   * Updates fields in the document referred to by this DocumentReference.
   * The update will fail if applied to a document that does not exist. Nested
   * fields can be updated by providing dot-separated field path strings or by providing FieldPath objects.
   *
   * @param documentRef DocumentReference A reference to the document to be updated. Value must not be null.
   * @param args any Either an object containing all of the fields and values to update,
   *        or a series of arguments alternating between fields (as string or FieldPath
   *        objects) and values.
   *
   * @returns {Transaction}
   */
  update(documentRef: DocumentReference, ...args: Array<any>): Transaction {
    // todo validate doc ref
    let data = {};
    Eif (args.length === 1) {
      Iif (!isObject(args[0])) {
        throw new Error(
          'Transaction.update failed: If using a single data argument, it must be an object.'
        );
      }
 
      [data] = args;
    } else if (args.length % 2 === 1) {
      throw new Error(
        'Transaction.update failed: Must have either a single object data argument, or equal numbers of data key/value pairs.'
      );
    } else {
      for (let i = 0; i < args.length; i += 2) {
        const key = args[i];
        const value = args[i + 1];
        if (isString(key)) {
          data[key] = value;
        } else if (key instanceof FieldPath) {
          data = mergeFieldPathData(data, key._segments, value);
        } else {
          throw new Error(
            `Transaction.update failed: Argument at index ${i} must be a string or FieldPath`
          );
        }
      }
    }
 
    this._commandBuffer.push({
      type: 'update',
      path: documentRef.path,
      data: buildNativeMap(data),
    });
 
    return this;
  }
 
  /**
   * Deletes the document referred to by the provided DocumentReference.
   *
   * @param documentRef DocumentReference A reference to the document to be deleted. Value must not be null.
   *
   * @returns {Transaction}
   */
  delete(documentRef: DocumentReference): Transaction {
    // todo validate doc ref
    this._commandBuffer.push({
      type: 'delete',
      path: documentRef.path,
    });
 
    return this;
  }
}