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 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 | 2× 2× 1334× 1334× 1334× 1334× 1334× 1334× 790× 10× 10× 2× 2× 2× 24× 24× 12× 4× 4× 4× 4× 4× 4× 4× 4× 4× 186× 184× 184× 26× 26× 26× 184× 2× 19× 3× 16× 16× 16× 2× 2× 14× 14× 18× 18× 18× 18× 12× 12× 12× 12× 4× 2× 2× 8× 8× 8× 474× 10× 8× 344× 340× 2× 4× 14× 14× 14× 14× 83× 1688× 14× 717× 717× 804× 693× 111× 93× 2× 91× 2× 89× 2× 87× 2× 85× 2× 83× 83× 83× 83× 83× 83× 83× 2× 83× 83× 83× 70× 46× 24× 2× 22× 22× 18× 18× 16× 16× 4× 4× 4× | /** * @flow * Database Reference representation wrapper */ import Query from './Query'; import DataSnapshot from './DataSnapshot'; import OnDisconnect from './OnDisconnect'; import { getLogger } from '../../utils/log'; import { getNativeModule } from '../../utils/native'; import ReferenceBase from '../../utils/ReferenceBase'; import { promiseOrCallback, isFunction, isObject, isString, tryJSONParse, tryJSONStringify, generatePushID, } from '../../utils'; import SyncTree from '../../utils/SyncTree'; import type Database from './'; import type { DatabaseModifier, FirebaseError } from '../../types'; // track all event registrations by path let listeners = 0; /** * Enum for event types * @readonly * @enum {String} */ const ReferenceEventTypes = { value: 'value', child_added: 'child_added', child_removed: 'child_removed', child_changed: 'child_changed', child_moved: 'child_moved', }; type DatabaseListener = { listenerId: number, eventName: string, successCallback: Function, failureCallback?: Function, }; /** * @typedef {String} ReferenceLocation - Path to location in the database, relative * to the root reference. Consists of a path where segments are separated by a * forward slash (/) and ends in a ReferenceKey - except the root location, which * has no ReferenceKey. * * @example * // root reference location: '/' * // non-root reference: '/path/to/referenceKey' */ /** * @typedef {String} ReferenceKey - Identifier for each location that is unique to that * location, within the scope of its parent. The last part of a ReferenceLocation. */ /** * Represents a specific location in your Database that can be used for * reading or writing data. * * You can reference the root using firebase.database().ref() or a child location * by calling firebase.database().ref("child/path"). * * @link https://firebase.google.com/docs/reference/js/firebase.database.Reference * @class Reference * @extends ReferenceBase */ export default class Reference extends ReferenceBase { _database: Database; _promise: ?Promise<*>; _query: Query; _refListeners: { [listenerId: number]: DatabaseListener }; constructor( database: Database, path: string, existingModifiers?: Array<DatabaseModifier> ) { super(path); this._promise = null; this._refListeners = {}; this._database = database; this._query = new Query(this, existingModifiers); getLogger(database).debug('Created new Reference', this._getRefKey()); } /** * By calling `keepSynced(true)` on a location, the data for that location will * automatically be downloaded and kept in sync, even when no listeners are * attached for that location. Additionally, while a location is kept synced, * it will not be evicted from the persistent disk cache. * * @link https://firebase.google.com/docs/reference/android/com/google/firebase/database/Query.html#keepSynced(boolean) * @param bool * @returns {*} */ keepSynced(bool: boolean): Promise<void> { return getNativeModule(this._database).keepSynced( this._getRefKey(), this.path, this._query.getModifiers(), bool ); } /** * Writes data to this Database location. * * @link https://firebase.google.com/docs/reference/js/firebase.database.Reference#set * @param value * @param onComplete * @returns {Promise} */ set(value: any, onComplete?: Function): Promise<void> { return promiseOrCallback( getNativeModule(this._database).set( this.path, this._serializeAnyType(value) ), onComplete ); } /** * Sets a priority for the data at this Database location. * * @link https://firebase.google.com/docs/reference/js/firebase.database.Reference#setPriority * @param priority * @param onComplete * @returns {Promise} */ setPriority( priority: string | number | null, onComplete?: Function ): Promise<void> { const _priority = this._serializeAnyType(priority); return promiseOrCallback( getNativeModule(this._database).setPriority(this.path, _priority), onComplete ); } /** * Writes data the Database location. Like set() but also specifies the priority for that data. * * @link https://firebase.google.com/docs/reference/js/firebase.database.Reference#setWithPriority * @param value * @param priority * @param onComplete * @returns {Promise} */ setWithPriority( value: any, priority: string | number | null, onComplete?: Function ): Promise<void> { const _value = this._serializeAnyType(value); const _priority = this._serializeAnyType(priority); return promiseOrCallback( getNativeModule(this._database).setWithPriority( this.path, _value, _priority ), onComplete ); } /** * Writes multiple values to the Database at once. * * @link https://firebase.google.com/docs/reference/js/firebase.database.Reference#update * @param val * @param onComplete * @returns {Promise} */ update(val: Object, onComplete?: Function): Promise<void> { const value = this._serializeObject(val); return promiseOrCallback( getNativeModule(this._database).update(this.path, value), onComplete ); } /** * Removes the data at this Database location. * * @link https://firebase.google.com/docs/reference/js/firebase.database.Reference#remove * @param onComplete * @return {Promise} */ remove(onComplete?: Function): Promise<void> { return promiseOrCallback( getNativeModule(this._database).remove(this.path), onComplete ); } /** * Atomically modifies the data at this location. * * @link https://firebase.google.com/docs/reference/js/firebase.database.Reference#transaction * @param transactionUpdate * @param onComplete * @param applyLocally */ transaction( transactionUpdate: Function, onComplete: ( error: ?Error, committed: boolean, snapshot: ?DataSnapshot ) => *, applyLocally: boolean = false ) { Iif (!isFunction(transactionUpdate)) { return Promise.reject( new Error('Missing transactionUpdate function argument.') ); } return new Promise((resolve, reject) => { const onCompleteWrapper = (error, committed, snapshotData) => { Eif (isFunction(onComplete)) { Iif (error) { onComplete(error, committed, null); } else { onComplete(null, committed, new DataSnapshot(this, snapshotData)); } } Iif (error) return reject(error); return resolve({ committed, snapshot: new DataSnapshot(this, snapshotData), }); }; // start the transaction natively this._database._transactionHandler.add( this, transactionUpdate, onCompleteWrapper, applyLocally ); }); } /** * * @param eventName * @param successCallback * @param cancelOrContext * @param context * @returns {Promise.<any>} */ once( eventName: string = 'value', successCallback: (snapshot: DataSnapshot) => void, cancelOrContext: (error: FirebaseError) => void, context?: Object ) { return getNativeModule(this._database) .once(this._getRefKey(), this.path, this._query.getModifiers(), eventName) .then(({ snapshot }) => { const _snapshot = new DataSnapshot(this, snapshot); if (isFunction(successCallback)) { Iif (isObject(cancelOrContext)) successCallback.bind(cancelOrContext)(_snapshot); Iif (context && isObject(context)) successCallback.bind(context)(_snapshot); successCallback(_snapshot); } return _snapshot; }) .catch(error => { Eif (isFunction(cancelOrContext)) return cancelOrContext(error); throw error; }); } /** * * @param value * @param onComplete * @returns {*} */ push(value: any, onComplete?: Function): Reference | Promise<void> { if (value === null || value === undefined) { return new Reference( this._database, `${this.path}/${generatePushID(this._database._serverTimeOffset)}` ); } const newRef = new Reference( this._database, `${this.path}/${generatePushID(this._database._serverTimeOffset)}` ); const promise = newRef.set(value); // if callback provided then internally call the set promise with value if (isFunction(onComplete)) { return ( promise // $FlowExpectedError: Reports that onComplete can change to null despite the null check: https://github.com/facebook/flow/issues/1655 .then(() => onComplete(null, newRef)) // $FlowExpectedError: Reports that onComplete can change to null despite the null check: https://github.com/facebook/flow/issues/1655 .catch(error => onComplete(error, null)) ); } // otherwise attach promise to 'thenable' reference and return the // new reference newRef._setThenable(promise); return newRef; } /** * MODIFIERS */ /** * * @returns {Reference} */ orderByKey(): Reference { return this.orderBy('orderByKey'); } /** * * @returns {Reference} */ orderByPriority(): Reference { return this.orderBy('orderByPriority'); } /** * * @returns {Reference} */ orderByValue(): Reference { return this.orderBy('orderByValue'); } /** * * @param key * @returns {Reference} */ orderByChild(key: string): Reference { return this.orderBy('orderByChild', key); } /** * * @param name * @param key * @returns {Reference} */ orderBy(name: string, key?: string): Reference { const newRef = new Reference( this._database, this.path, this._query.getModifiers() ); newRef._query.orderBy(name, key); return newRef; } /** * LIMITS */ /** * * @param limit * @returns {Reference} */ limitToLast(limit: number): Reference { return this.limit('limitToLast', limit); } /** * * @param limit * @returns {Reference} */ limitToFirst(limit: number): Reference { return this.limit('limitToFirst', limit); } /** * * @param name * @param limit * @returns {Reference} */ limit(name: string, limit: number): Reference { const newRef = new Reference( this._database, this.path, this._query.getModifiers() ); newRef._query.limit(name, limit); return newRef; } /** * FILTERS */ /** * * @param value * @param key * @returns {Reference} */ equalTo(value: any, key?: string): Reference { return this.filter('equalTo', value, key); } /** * * @param value * @param key * @returns {Reference} */ endAt(value: any, key?: string): Reference { return this.filter('endAt', value, key); } /** * * @param value * @param key * @returns {Reference} */ startAt(value: any, key?: string): Reference { return this.filter('startAt', value, key); } /** * * @param name * @param value * @param key * @returns {Reference} */ filter(name: string, value: any, key?: string): Reference { const newRef = new Reference( this._database, this.path, this._query.getModifiers() ); newRef._query.filter(name, value, key); return newRef; } /** * * @returns {OnDisconnect} */ onDisconnect(): OnDisconnect { return new OnDisconnect(this); } /** * Creates a Reference to a child of the current Reference, using a relative path. * No validation is performed on the path to ensure it has a valid format. * @param {String} path relative to current ref's location * @returns {!Reference} A new Reference to the path provided, relative to the current * Reference * {@link https://firebase.google.com/docs/reference/js/firebase.database.Reference#child} */ child(path: string): Reference { return new Reference(this._database, `${this.path}/${path}`); } /** * Return the ref as a path string * @returns {string} */ toString(): string { return `${this._database.app.options.databaseURL}/${this.path}`; } /** * Returns whether another Reference represent the same location and are from the * same instance of firebase.app.App - multiple firebase apps not currently supported. * @param {Reference} otherRef - Other reference to compare to this one * @return {Boolean} Whether otherReference is equal to this one * * {@link https://firebase.google.com/docs/reference/js/firebase.database.Reference#isEqual} */ isEqual(otherRef: Reference): boolean { return ( !!otherRef && otherRef.constructor === Reference && otherRef.key === this.key && this._query.queryIdentifier() === otherRef._query.queryIdentifier() ); } /** * GETTERS */ /** * The parent location of a Reference, or null for the root Reference. * @type {Reference} * * {@link https://firebase.google.com/docs/reference/js/firebase.database.Reference#parent} */ get parent(): Reference | null { if (this.path === '/') return null; return new Reference( this._database, this.path.substring(0, this.path.lastIndexOf('/')) ); } /** * A reference to itself * @type {!Reference} * * {@link https://firebase.google.com/docs/reference/js/firebase.database.Reference#ref} */ get ref(): Reference { return this; } /** * Reference to the root of the database: '/' * @type {!Reference} * * {@link https://firebase.google.com/docs/reference/js/firebase.database.Reference#root} */ get root(): Reference { return new Reference(this._database, '/'); } /** * Access then method of promise if set * @return {*} */ then(fnResolve: any => any, fnReject: any => any) { Eif (isFunction(fnResolve) && this._promise && this._promise.then) { return this._promise.then.bind(this._promise)( result => { this._promise = null; return fnResolve(result); }, possibleErr => { this._promise = null; if (isFunction(fnReject)) { return fnReject(possibleErr); } throw possibleErr; } ); } throw new Error("Cannot read property 'then' of undefined."); } /** * Access catch method of promise if set * @return {*} */ catch(fnReject: any => any) { if (isFunction(fnReject) && this._promise && this._promise.catch) { return this._promise.catch.bind(this._promise)(possibleErr => { this._promise = null; return fnReject(possibleErr); }); } throw new Error("Cannot read property 'catch' of undefined."); } /** * INTERNALS */ /** * Generate a unique registration key. * * @return {string} */ _getRegistrationKey(eventType: string): string { return `$${this._database.app.name}$/${ this.path }$${this._query.queryIdentifier()}$${listeners}$${eventType}`; } /** * Generate a string that uniquely identifies this * combination of path and query modifiers * * @return {string} * @private */ _getRefKey(): string { return `$${this._database.app.name}$/${ this.path }$${this._query.queryIdentifier()}`; } /** * Set the promise this 'thenable' reference relates to * @param promise * @private */ _setThenable(promise: Promise<*>) { this._promise = promise; } /** * * @param obj * @returns {Object} * @private */ _serializeObject(obj: Object) { Iif (!isObject(obj)) return obj; // json stringify then parse it calls toString on Objects / Classes // that support it i.e new Date() becomes a ISO string. return tryJSONParse(tryJSONStringify(obj)); } /** * * @param value * @returns {*} * @private */ _serializeAnyType(value: any) { if (isObject(value)) { return { type: 'object', value: this._serializeObject(value), }; } return { type: typeof value, value, }; } /** * Register a listener for data changes at the current ref's location. * The primary method of reading data from a Database. * * Listeners can be unbound using {@link off}. * * Event Types: * * - value: {@link callback}. * - child_added: {@link callback} * - child_removed: {@link callback} * - child_changed: {@link callback} * - child_moved: {@link callback} * * @param {ReferenceEventType} eventType - Type of event to attach a callback for. * @param {ReferenceEventCallback} callback - Function that will be called * when the event occurs with the new data. * @param {cancelCallbackOrContext=} cancelCallbackOrContext - Optional callback that is called * if the event subscription fails. {@link cancelCallbackOrContext} * @param {*=} context - Optional object to bind the callbacks to when calling them. * @returns {ReferenceEventCallback} callback function, unmodified (unbound), for * convenience if you want to pass an inline function to on() and store it later for * removing using off(). * * {@link https://firebase.google.com/docs/reference/js/firebase.database.Reference#on} */ on( eventType: string, callback: DataSnapshot => any, cancelCallbackOrContext?: Object => any | Object, context?: Object ): Function { if (!eventType) { throw new Error( 'Query.on failed: Function called with 0 arguments. Expects at least 2.' ); } if (!isString(eventType) || !ReferenceEventTypes[eventType]) { throw new Error( `Query.on failed: First argument must be a valid string event type: "${Object.keys( ReferenceEventTypes ).join(', ')}"` ); } if (!callback) { throw new Error( 'Query.on failed: Function called with 1 argument. Expects at least 2.' ); } if (!isFunction(callback)) { throw new Error( 'Query.on failed: Second argument must be a valid function.' ); } if ( cancelCallbackOrContext && !isFunction(cancelCallbackOrContext) && !isObject(context) && !isObject(cancelCallbackOrContext) ) { throw new Error( 'Query.on failed: Function called with 3 arguments, but third optional argument `cancelCallbackOrContext` was not a function.' ); } Iif ( cancelCallbackOrContext && !isFunction(cancelCallbackOrContext) && context ) { throw new Error( 'Query.on failed: Function called with 4 arguments, but third optional argument `cancelCallbackOrContext` was not a function.' ); } const eventRegistrationKey = this._getRegistrationKey(eventType); const registrationCancellationKey = `${eventRegistrationKey}$cancelled`; const _context = cancelCallbackOrContext && !isFunction(cancelCallbackOrContext) ? cancelCallbackOrContext : context; const registrationObj = { eventType, ref: this, path: this.path, key: this._getRefKey(), appName: this._database.app.name, eventRegistrationKey, }; SyncTree.addRegistration({ ...registrationObj, listener: _context ? callback.bind(_context) : callback, }); if (cancelCallbackOrContext && isFunction(cancelCallbackOrContext)) { // cancellations have their own separate registration // as these are one off events, and they're not guaranteed // to occur either, only happens on failure to register on native SyncTree.addRegistration({ ref: this, once: true, path: this.path, key: this._getRefKey(), appName: this._database.app.name, eventType: `${eventType}$cancelled`, eventRegistrationKey: registrationCancellationKey, listener: _context ? cancelCallbackOrContext.bind(_context) : cancelCallbackOrContext, }); } // initialise the native listener if not already listening getNativeModule(this._database).on({ eventType, path: this.path, key: this._getRefKey(), appName: this._database.app.name, modifiers: this._query.getModifiers(), hasCancellationCallback: isFunction(cancelCallbackOrContext), registration: { eventRegistrationKey, key: registrationObj.key, registrationCancellationKey, }, }); // increment number of listeners - just s short way of making // every registration unique per .on() call listeners += 1; // return original unbound successCallback for // the purposes of calling .off(eventType, callback) at a later date return callback; } /** * Detaches a callback previously attached with on(). * * Detach a callback previously attached with on(). Note that if on() was called * multiple times with the same eventType and callback, the callback will be called * multiple times for each event, and off() must be called multiple times to * remove the callback. Calling off() on a parent listener will not automatically * remove listeners registered on child nodes, off() must also be called on any * child listeners to remove the callback. * * If a callback is not specified, all callbacks for the specified eventType will be removed. * Similarly, if no eventType or callback is specified, all callbacks for the Reference will be removed. * @param eventType * @param originalCallback */ off(eventType?: string = '', originalCallback?: () => any) { if (!arguments.length) { // Firebase Docs: // if no eventType or callback is specified, all callbacks for the Reference will be removed. return SyncTree.removeListenersForRegistrations( SyncTree.getRegistrationsByPath(this.path) ); } /* * VALIDATE ARGS */ if ( eventType && (!isString(eventType) || !ReferenceEventTypes[eventType]) ) { throw new Error( `Query.off failed: First argument must be a valid string event type: "${Object.keys( ReferenceEventTypes ).join(', ')}"` ); } Iif (originalCallback && !isFunction(originalCallback)) { throw new Error( 'Query.off failed: Function called with 2 arguments, but second optional argument was not a function.' ); } // Firebase Docs: // Note that if on() was called // multiple times with the same eventType and callback, the callback will be called // multiple times for each event, and off() must be called multiple times to // remove the callback. // Remove only a single registration if (eventType && originalCallback) { const registration = SyncTree.getOneByPathEventListener( this.path, eventType, originalCallback ); if (!registration) return []; // remove the paired cancellation registration if any exist SyncTree.removeListenersForRegistrations([`${registration}$cancelled`]); // remove only the first registration to match firebase web sdk // call multiple times to remove multiple registrations return SyncTree.removeListenerRegistrations(originalCallback, [ registration, ]); } // Firebase Docs: // If a callback is not specified, all callbacks for the specified eventType will be removed. const registrations = SyncTree.getRegistrationsByPathEvent( this.path, eventType ); SyncTree.removeListenersForRegistrations( SyncTree.getRegistrationsByPathEvent(this.path, `${eventType}$cancelled`) ); return SyncTree.removeListenersForRegistrations(registrations); } } |