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

76.36% Statements 42/55
50% Branches 9/18
90.91% Functions 10/11
77.36% Lines 41/53
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 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247                                                                                                                                                                                                                        14×                                                                                                                                                                                                    
/**
 * @flow
 * Firestore Transaction representation wrapper
 */
import { getAppEventName, SharedEventEmitter } from '../../utils/events';
import { getLogger } from '../../utils/log';
import { getNativeModule } from '../../utils/native';
import Transaction from './Transaction';
import type Firestore from './';
 
let transactionId = 0;
 
/**
 * Uses the push id generator to create a transaction id
 * @returns {number}
 * @private
 */
const generateTransactionId = (): number => transactionId++;
 
export type TransactionMeta = {
  id: number,
  stack: string[],
  reject?: Function,
  resolve?: Function,
  transaction: Transaction,
  updateFunction: (transaction: Transaction) => Promise<any>,
};
 
type TransactionEvent = {
  id: number,
  type: 'update' | 'error' | 'complete',
  error: ?{ code: string, message: string },
};
 
/**
 * @class TransactionHandler
 */
export default class TransactionHandler {
  _firestore: Firestore;
  _pending: {
    [number]: {
      meta: TransactionMeta,
      transaction: Transaction,
    },
  };
 
  constructor(firestore: Firestore) {
    this._pending = {};
    this._firestore = firestore;
    SharedEventEmitter.addListener(
      getAppEventName(this._firestore, 'firestore_transaction_event'),
      this._handleTransactionEvent.bind(this)
    );
  }
 
  /**
   * -------------
   * INTERNAL API
   * -------------
   */
 
  /**
   * Add a new transaction and start it natively.
   * @param updateFunction
   */
  _add(
    updateFunction: (transaction: Transaction) => Promise<any>
  ): Promise<any> {
    const id = generateTransactionId();
    // $FlowExpectedError: Transaction has to be populated
    const meta: TransactionMeta = {
      id,
      updateFunction,
      stack: new Error().stack
        .split('\n')
        .slice(4)
        .join('\n'),
    };
 
    this._pending[id] = {
      meta,
      transaction: new Transaction(this._firestore, meta),
    };
 
    // deferred promise
    return new Promise((resolve, reject) => {
      getNativeModule(this._firestore).transactionBegin(id);
      meta.resolve = r => {
        resolve(r);
        this._remove(id);
      };
      meta.reject = e => {
        reject(e);
        this._remove(id);
      };
    });
  }
 
  /**
   * Destroys a local instance of a transaction meta
   *
   * @param id
   * @private
   */
  _remove(id) {
    // todo confirm pending arg no longer needed
    getNativeModule(this._firestore).transactionDispose(id);
    // TODO may need delaying to next event loop
    delete this._pending[id];
  }
 
  /**
   * -------------
   *    EVENTS
   * -------------
   */
 
  /**
   * Handles incoming native transaction events and distributes to correct
   * internal handler by event.type
   *
   * @param event
   * @returns {*}
   * @private
   */
  _handleTransactionEvent(event: TransactionEvent) {
    switch (event.type) {
      case 'update':
        return this._handleUpdate(event);
      case 'error':
        return this._handleError(event);
      case 'complete':
        return this._handleComplete(event);
      default:
        getLogger(this._firestore).warn(
          `Unknown transaction event type: '${event.type}'`,
          event
        );
        return undefined;
    }
  }
 
  /**
   * Handles incoming native transaction update events
   *
   * @param event
   * @private
   */
  async _handleUpdate(event: TransactionEvent) {
    const { id } = event;
    // abort if no longer exists js side
    Iif (!this._pending[id]) return this._remove(id);
 
    const { meta, transaction } = this._pending[id];
    const { updateFunction, reject } = meta;
 
    // clear any saved state from previous transaction runs
    transaction._prepare();
 
    let finalError;
    let updateFailed;
    let pendingResult;
 
    // run the users custom update functionality
    try {
      const possiblePromise = updateFunction(transaction);
 
      // validate user has returned a promise in their update function
      // TODO must it actually return a promise? Can't find any usages of it without one...
      Iif (!possiblePromise || !possiblePromise.then) {
        finalError = new Error(
          'Update function for `firestore.runTransaction(updateFunction)` must return a Promise.'
        );
      } else {
        pendingResult = await possiblePromise;
      }
    } catch (exception) {
      // exception can still be falsey if user `Promise.reject();` 's with no args
      // so we track the exception with a updateFailed boolean to ensure no fall-through
      updateFailed = true;
      finalError = exception;
    }
 
    // reject the final promise and remove from native
    // update is failed when either the users updateFunction
    // throws an error or rejects a promise
    if (updateFailed) {
      // $FlowExpectedError: Reject will always be present
      return reject(finalError);
    }
 
    // capture the resolved result as we'll need this
    // to resolve the runTransaction() promise when
    // native emits that the transaction is final
    transaction._pendingResult = pendingResult;
 
    // send the buffered update/set/delete commands for native to process
    return getNativeModule(this._firestore).transactionApplyBuffer(
      id,
      transaction._commandBuffer
    );
  }
 
  /**
   * Handles incoming native transaction error events
   *
   * @param event
   * @private
   */
  _handleError(event: TransactionEvent) {
    const { id, error } = event;
    const { meta } = this._pending[id];
 
    if (meta && error) {
      const { code, message } = error;
      // build a JS error and replace its stack
      // with the captured one at start of transaction
      // so it's actually relevant to the user
      const errorWithStack = new Error(message);
      // $FlowExpectedError: code is needed for Firebase errors
      errorWithStack.code = code;
      // $FlowExpectedError: stack should be a stack trace
      errorWithStack.stack = meta.stack;
 
      // $FlowExpectedError: Reject will always be present
      meta.reject(errorWithStack);
    }
  }
 
  /**
   * Handles incoming native transaction complete events
   *
   * @param event
   * @private
   */
  _handleComplete(event: TransactionEvent) {
    const { id } = event;
    const { meta, transaction } = this._pending[id];
 
    Eif (meta) {
      const pendingResult = transaction._pendingResult;
      // $FlowExpectedError: Resolve will always be present
      meta.resolve(pendingResult);
    }
  }
}