All files / core/view EventRegistration.ts

79.52% Statements 66/83
69.44% Branches 25/36
76.19% Functions 16/21
79.01% Lines 64/81
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 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304                                12x 12x 12x 12x                                                                                                                             12x             471x 471x 471x           12x 1054x           12x 460x 460x                   12x 460x 460x                     460x 460x 460x               12x                     12x 171x   171x   5x   166x                 12x 149x   12x                     12x             91x     91x 91x           12x   466x 466x   466x           12x                     12x 166x 166x 166x 166x                     12x 166x 166x                     166x 166x 166x                       12x 13x 6x 2x 4x 3x 3x 3x         3x 3x 3x 3x                                 8x           12x 5x   12x  
/**
 * Copyright 2017 Google Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
 
import { DataSnapshot } from '../../api/DataSnapshot';
import { DataEvent, CancelEvent, Event } from './Event';
import { contains, getCount, getAnyKey, every } from '@firebase/util';
import { assert } from '@firebase/util';
import { Path } from '../util/Path';
import { Change } from './Change';
import { Query } from '../../api/Query';
 
/**
 * An EventRegistration is basically an event type ('value', 'child_added', etc.) and a callback
 * to be notified of that type of event.
 *
 * That said, it can also contain a cancel callback to be notified if the event is canceled.  And
 * currently, this code is organized around the idea that you would register multiple child_ callbacks
 * together, as a single EventRegistration.  Though currently we don't do that.
 */
export interface EventRegistration {
  /**
   * True if this container has a callback to trigger for this event type
   * @param {!string} eventType
   * @return {boolean}
   */
  respondsTo(eventType: string): boolean;
 
  /**
   * @param {!Change} change
   * @param {!Query} query
   * @return {!Event}
   */
  createEvent(change: Change, query: Query): Event;
 
  /**
   * Given event data, return a function to trigger the user's callback
   * @param {!Event} eventData
   * @return {function()}
   */
  getEventRunner(eventData: Event): () => void;
 
  /**
   * @param {!Error} error
   * @param {!Path} path
   * @return {?CancelEvent}
   */
  createCancelEvent(error: Error, path: Path): CancelEvent | null;
 
  /**
   * @param {!EventRegistration} other
   * @return {boolean}
   */
  matches(other: EventRegistration): boolean;
 
  /**
   * False basically means this is a "dummy" callback container being used as a sentinel
   * to remove all callback containers of a particular type.  (e.g. if the user does
   * ref.off('value') without specifying a specific callback).
   *
   * (TODO: Rework this, since it's hacky)
   *
   * @return {boolean}
   */
  hasAnyCallback(): boolean;
}
 
/**
 * Represents registration for 'value' events.
 */
export class ValueEventRegistration implements EventRegistration {
  /**
   * @param {?function(!DataSnapshot)} callback_
   * @param {?function(Error)} cancelCallback_
   * @param {?Object} context_
   */
  constructor(
    private callback_: ((d: DataSnapshot) => void) | null,
    private cancelCallback_: ((e: Error) => void) | null,
    private context_: Object | null
  ) {}
 
  /**
   * @inheritDoc
   */
  respondsTo(eventType: string): boolean {
    return eventType === 'value';
  }
 
  /**
   * @inheritDoc
   */
  createEvent(change: Change, query: Query): DataEvent {
    const index = query.getQueryParams().getIndex();
    return new DataEvent(
      'value',
      this,
      new DataSnapshot(change.snapshotNode, query.getRef(), index)
    );
  }
 
  /**
   * @inheritDoc
   */
  getEventRunner(eventData: CancelEvent | DataEvent): () => void {
    const ctx = this.context_;
    Iif (eventData.getEventType() === 'cancel') {
      assert(
        this.cancelCallback_,
        'Raising a cancel event on a listener with no cancel callback'
      );
      const cancelCB = this.cancelCallback_;
      return function() {
        // We know that error exists, we checked above that this is a cancel event
        cancelCB.call(ctx, (eventData as CancelEvent).error);
      };
    } else {
      const cb = this.callback_;
      return function() {
        cb.call(ctx, (eventData as DataEvent).snapshot);
      };
    }
  }
 
  /**
   * @inheritDoc
   */
  createCancelEvent(error: Error, path: Path): CancelEvent | null {
    if (this.cancelCallback_) {
      return new CancelEvent(this, error, path);
    } else {
      return null;
    }
  }
 
  /**
   * @inheritDoc
   */
  matches(other: EventRegistration): boolean {
    Iif (!(other instanceof ValueEventRegistration)) {
      return false;
    } else if (!other.callback_ || !this.callback_) {
      // If no callback specified, we consider it to match any callback.
      return true;
    } else {
      return (
        other.callback_ === this.callback_ && other.context_ === this.context_
      );
    }
  }
 
  /**
   * @inheritDoc
   */
  hasAnyCallback(): boolean {
    return this.callback_ !== null;
  }
}
 
/**
 * Represents the registration of 1 or more child_xxx events.
 *
 * Currently, it is always exactly 1 child_xxx event, but the idea is we might let you
 * register a group of callbacks together in the future.
 *
 * @constructor
 * @implements {EventRegistration}
 */
export class ChildEventRegistration implements EventRegistration {
  /**
   * @param {?Object.<string, function(!DataSnapshot, ?string=)>} callbacks_
   * @param {?function(Error)} cancelCallback_
   * @param {Object=} context_
   */
  constructor(
    private callbacks_:
      | ({ [k: string]: (d: DataSnapshot, s?: string | null) => void })
      | null,
    private cancelCallback_: ((e: Error) => void) | null,
    private context_?: Object
  ) {}
 
  /**
   * @inheritDoc
   */
  respondsTo(eventType: string): boolean {
    let eventToCheck =
      eventType === 'children_added' ? 'child_added' : eventType;
    eventToCheck =
      eventToCheck === 'children_removed' ? 'child_removed' : eventToCheck;
    return contains(this.callbacks_, eventToCheck);
  }
 
  /**
   * @inheritDoc
   */
  createCancelEvent(error: Error, path: Path): CancelEvent | null {
    if (this.cancelCallback_) {
      return new CancelEvent(this, error, path);
    } else {
      return null;
    }
  }
 
  /**
   * @inheritDoc
   */
  createEvent(change: Change, query: Query): DataEvent {
    assert(change.childName != null, 'Child events should have a childName.');
    const ref = query.getRef().child(/** @type {!string} */ (change.childName));
    const index = query.getQueryParams().getIndex();
    return new DataEvent(
      change.type as any,
      this,
      new DataSnapshot(change.snapshotNode, ref, index as any),
      change.prevName
    );
  }
 
  /**
   * @inheritDoc
   */
  getEventRunner(eventData: CancelEvent | DataEvent): () => void {
    const ctx = this.context_;
    Iif (eventData.getEventType() === 'cancel') {
      assert(
        this.cancelCallback_,
        'Raising a cancel event on a listener with no cancel callback'
      );
      const cancelCB = this.cancelCallback_;
      return function() {
        // We know that error exists, we checked above that this is a cancel event
        cancelCB.call(ctx, (eventData as CancelEvent).error);
      };
    } else {
      const cb = this.callbacks_[(eventData as DataEvent).eventType];
      return function() {
        cb.call(
          ctx,
          (eventData as DataEvent).snapshot,
          (eventData as DataEvent).prevName
        );
      };
    }
  }
 
  /**
   * @inheritDoc
   */
  matches(other: EventRegistration): boolean {
    if (other instanceof ChildEventRegistration) {
      if (!this.callbacks_ || !other.callbacks_) {
        return true;
      } else if (this.context_ === other.context_) {
        const otherCount = getCount(other.callbacks_);
        const thisCount = getCount(this.callbacks_);
        Eif (otherCount === thisCount) {
          // If count is 1, do an exact match on eventType, if either is defined but null, it's a match.
          //  If event types don't match, not a match
          // If count is not 1, exact match across all
 
          Eif (otherCount === 1) {
            const otherKey /** @type {!string} */ = getAnyKey(other.callbacks_);
            const thisKey /** @type {!string} */ = getAnyKey(this.callbacks_);
            return (
              thisKey === otherKey &&
              (!other.callbacks_[otherKey] ||
                !this.callbacks_[thisKey] ||
                other.callbacks_[otherKey] === this.callbacks_[thisKey])
            );
          } else {
            // Exact match on each key.
            return every(
              this.callbacks_,
              (eventType, cb) => other.callbacks_[eventType] === cb
            );
          }
        }
      }
    }
 
    return false;
  }
 
  /**
   * @inheritDoc
   */
  hasAnyCallback(): boolean {
    return this.callbacks_ !== null;
  }
}