all files / firebase/modules/storage/ task.js

59.62% Statements 31/52
38.24% Branches 13/34
54.55% Functions 6/11
60% Lines 30/50
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                                                                                                                10× 10× 10× 10×     10× 10×                   11× 11× 11× 11×                                                                                                                                                                                                                                              
/**
 * @flow
 * UploadTask representation wrapper
 */
import { statics as StorageStatics } from './';
import { isFunction } from './../../utils';
import type Storage from './';
import type StorageReference from './reference';
 
export const UPLOAD_TASK = 'upload';
export const DOWNLOAD_TASK = 'download';
 
declare type UploadTaskSnapshotType = {
  bytesTransferred: number,
  downloadURL: string | null,
  metadata: Object, // TODO flow type def for https://firebase.google.com/docs/reference/js/firebase.storage.FullMetadata.html
  ref: StorageReference,
  state:
    | typeof StorageStatics.TaskState.RUNNING
    | typeof StorageStatics.TaskState.PAUSED
    | typeof StorageStatics.TaskState.SUCCESS
    | typeof StorageStatics.TaskState.CANCELLED
    | typeof StorageStatics.TaskState.ERROR,
  task: StorageTask,
  totalBytes: number,
};
 
declare type FuncSnapshotType =
  | null
  | ((snapshot: UploadTaskSnapshotType) => any);
 
declare type FuncErrorType = null | ((error: Error) => any);
 
declare type NextOrObserverType =
  | null
  | {
      next?: FuncSnapshotType,
      error?: FuncErrorType,
      complete?: FuncSnapshotType,
    }
  | FuncSnapshotType;
 
/**
 * @url https://firebase.google.com/docs/reference/js/firebase.storage.UploadTask
 */
export default class StorageTask {
  type: typeof UPLOAD_TASK | typeof DOWNLOAD_TASK;
  ref: StorageReference;
  storage: Storage;
  path: string;
  then: () => Promise<*>;
  catch: () => Promise<*>;
 
  constructor(
    type: typeof UPLOAD_TASK | typeof DOWNLOAD_TASK,
    promise: Promise<*>,
    storageRef: StorageReference
  ) {
    this.type = type;
    this.ref = storageRef;
    this.storage = storageRef._storage;
    this.path = storageRef.path;
 
    // 'proxy' original promise
    this.then = promise.then.bind(promise);
    this.catch = promise.catch.bind(promise);
  }
 
  /**
   * Intercepts a native snapshot result object attaches ref / task instances
   * and calls the original function
   * @returns {Promise.<T>}
   * @private
   */
  _interceptSnapshotEvent(f: ?Function): null | (() => *) {
    if (!isFunction(f)) return null;
    return snapshot => {
      const _snapshot = Object.assign({}, snapshot);
      _snapshot.task = this;
      _snapshot.ref = this.ref;
      return f && f(_snapshot);
    };
  }
 
  /**
   * Intercepts a error object form native and converts to a JS Error
   * @param f
   * @returns {*}
   * @private
   */
  _interceptErrorEvent(f: ?Function): null | (Error => *) {
    Iif (!isFunction(f)) return null;
    return error => {
      const _error = new Error(error.message);
      // $FlowExpectedError
      _error.code = error.code;
      return f && f(_error);
    };
  }
 
  /**
   *
   * @param nextOrObserver
   * @param error
   * @param complete
   * @returns {function()}
   * @private
   */
  _subscribe(
    nextOrObserver: NextOrObserverType,
    error: FuncErrorType,
    complete: FuncSnapshotType
  ): Function {
    let _error;
    let _next;
    let _complete;
 
    Eif (typeof nextOrObserver === 'function') {
      _error = this._interceptErrorEvent(error);
      _next = this._interceptSnapshotEvent(nextOrObserver);
      _complete = this._interceptSnapshotEvent(complete);
    } else if (nextOrObserver) {
      _error = this._interceptErrorEvent(nextOrObserver.error);
      _next = this._interceptSnapshotEvent(nextOrObserver.next);
      _complete = this._interceptSnapshotEvent(nextOrObserver.complete);
    }
 
    Eif (_next) {
      this.storage._addListener(
        this.path,
        StorageStatics.TaskEvent.STATE_CHANGED,
        _next
      );
    }
    Eif (_error) {
      this.storage._addListener(this.path, `${this.type}_failure`, _error);
    }
    Iif (_complete) {
      this.storage._addListener(this.path, `${this.type}_success`, _complete);
    }
 
    return () => {
      if (_next)
        this.storage._removeListener(
          this.path,
          StorageStatics.TaskEvent.STATE_CHANGED,
          _next
        );
      if (_error)
        this.storage._removeListener(this.path, `${this.type}_failure`, _error);
      if (_complete)
        this.storage._removeListener(
          this.path,
          `${this.type}_success`,
          _complete
        );
    };
  }
 
  /**
   *
   * @param event
   * @param nextOrObserver
   * @param error
   * @param complete
   * @returns {function()}
   */
  on(
    event: string = StorageStatics.TaskEvent.STATE_CHANGED,
    nextOrObserver: NextOrObserverType,
    error: FuncErrorType,
    complete: FuncSnapshotType
  ): Function {
    Iif (!event) {
      throw new Error(
        "StorageTask.on listener is missing required string argument 'event'."
      );
    }
 
    Iif (event !== StorageStatics.TaskEvent.STATE_CHANGED) {
      throw new Error(
        `StorageTask.on event argument must be a string with a value of '${
          StorageStatics.TaskEvent.STATE_CHANGED
        }'`
      );
    }
 
    // if only event provided return the subscriber function
    Iif (!nextOrObserver && !error && !complete) {
      return this._subscribe.bind(this);
    }
 
    return this._subscribe(nextOrObserver, error, complete);
  }
 
  pause() {
    throw new Error(
      '.pause() is not currently supported by react-native-firebase'
    );
  }
 
  resume() {
    // todo
    throw new Error(
      '.resume() is not currently supported by react-native-firebase'
    );
  }
 
  cancel() {
    // todo
    throw new Error(
      '.cancel() is not currently supported by react-native-firebase'
    );
  }
}