/* * Copyright (c) 2016-present Invertase Limited & Contributors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this library 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 { isBoolean, isFunction, isIOS, isNull, isNumber, isObject, isString, isUndefined, pathIsEmpty, pathToUrlEncodedString, ReferenceBase, } from '@react-native-firebase/app/dist/module/common'; import DatabaseDataSnapshot from './DatabaseDataSnapshot'; import DatabaseSyncTree from './DatabaseSyncTree'; import type DatabaseQueryModifiers from './DatabaseQueryModifiers'; import type { DatabaseChildSnapshotResultInternal, DatabaseInternal, DatabaseListenPropsInternal, } from './types/internal'; import type { DatabaseReference, DataSnapshot, EventType, Query } from './types/database'; const eventTypes = [ 'value', 'child_added', 'child_changed', 'child_moved', 'child_removed', ] as const; /** `.info/*` is client-local metadata that only the listener path serves. */ const INFO_PATH = /^\/?\.info(\/|$)/; /** * True when native/web get already produced an observer-shaped `database/*` code. * Android Query.get() non-denial failures use SharedUtils.getExceptionMap → `database/unknown`; * those still fall through to `once('value')`. Specific codes mean once already ran (or a * denial was mapped to once's code) — do not ask the server again. */ function isObserverShapedDatabaseError(error: unknown): boolean { const code = (error as { code?: string } | null | undefined)?.code; return typeof code === 'string' && code.startsWith('database/') && code !== 'database/unknown'; } type DatabaseReferenceConstructor = new ( database: DatabaseInternal, path: string, ) => DatabaseReference; let DatabaseReferenceClass: DatabaseReferenceConstructor | null = null; export function provideReferenceClass(databaseReference: DatabaseReferenceConstructor): void { DatabaseReferenceClass = databaseReference; } function createReference(database: DatabaseInternal, path: string): DatabaseReference { if (!DatabaseReferenceClass) { throw new Error('DatabaseReference class has not been provided.'); } return new DatabaseReferenceClass(database, path); } let listeners = 0; export default class DatabaseQuery extends ReferenceBase implements Query { _database: DatabaseInternal; _modifiers: DatabaseQueryModifiers; constructor(database: DatabaseInternal, path: string, modifiers: DatabaseQueryModifiers) { super(path); this._database = database; this._modifiers = modifiers; } get ref(): DatabaseReference { return createReference(this._database, this.path); } endAt(value: number | string | boolean | null, key?: string): Query { if (!isNumber(value) && !isString(value) && !isBoolean(value) && !isNull(value)) { throw new Error( "firebase.database().ref().endAt(*) 'value' must be a number, string, boolean or null value.", ); } if (!isUndefined(key) && !isString(key)) { throw new Error( "firebase.database().ref().endAt(_, *) 'key' must be a string value if defined.", ); } if (this._modifiers.hasEndAt()) { throw new Error( 'firebase.database().ref().endAt() Ending point was already set (by another call to endAt or equalTo).', ); } const modifiers = this._modifiers._copy().endAt(value, key); modifiers.validateModifiers('firebase.database().ref().endAt()'); return new DatabaseQuery(this._database, this.path, modifiers); } equalTo(value: number | string | boolean | null, key?: string): Query { if (!isNumber(value) && !isString(value) && !isBoolean(value) && !isNull(value)) { throw new Error( "firebase.database().ref().equalTo(*) 'value' must be a number, string, boolean or null value.", ); } if (!isUndefined(key) && !isString(key)) { throw new Error( "firebase.database().ref().equalTo(_, *) 'key' must be a string value if defined.", ); } if (this._modifiers.hasStartAt()) { throw new Error( 'firebase.database().ref().equalTo() Starting point was already set (by another call to startAt or equalTo).', ); } if (this._modifiers.hasEndAt()) { throw new Error( 'firebase.database().ref().equalTo() Ending point was already set (by another call to endAt or equalTo).', ); } return (this.startAt(value, key) as DatabaseQuery).endAt(value, key); } isEqual(other: Query): boolean { if (!(other instanceof DatabaseQuery)) { throw new Error("firebase.database().ref().isEqual(*) 'other' must be an instance of Query."); } const sameApp = other._database.app === this._database.app; const sameDatabasePath = other.toString() === this.toString(); const sameModifiers = other._modifiers.toString() === this._modifiers.toString(); return sameApp && sameDatabasePath && sameModifiers; } limitToFirst(limit: number): Query { if (this._modifiers.isValidLimit(limit)) { throw new Error( "firebase.database().ref().limitToFirst(*) 'limit' must be a positive integer value.", ); } if (this._modifiers.hasLimit()) { throw new Error( 'firebase.database().ref().limitToFirst(*) Limit was already set (by another call to limitToFirst, or limitToLast)', ); } return new DatabaseQuery( this._database, this.path, this._modifiers._copy().limitToFirst(limit), ); } limitToLast(limit: number): Query { if (this._modifiers.isValidLimit(limit)) { throw new Error( "firebase.database().ref().limitToLast(*) 'limit' must be a positive integer value.", ); } if (this._modifiers.hasLimit()) { throw new Error( 'firebase.database().ref().limitToLast(*) Limit was already set (by another call to limitToFirst, or limitToLast)', ); } return new DatabaseQuery(this._database, this.path, this._modifiers._copy().limitToLast(limit)); } off( eventType?: EventType, callback?: (a: DataSnapshot, b?: string | null) => void, context?: Record, ): void { if (arguments.length === 0) { DatabaseSyncTree.removeListenersForRegistrations( DatabaseSyncTree.getRegistrationsByPath(this.path), ); return; } if (!isUndefined(eventType) && !eventTypes.includes(eventType)) { throw new Error( `firebase.database().ref().off(*) 'eventType' must be one of ${eventTypes.join(', ')}.`, ); } if (!isUndefined(callback) && !isFunction(callback)) { throw new Error("firebase.database().ref().off(_, *) 'callback' must be a function."); } if (!isUndefined(context) && !isNull(context) && !isObject(context)) { throw new Error("firebase.database().ref().off(_, _, *) 'context' must be an object."); } if (eventType && callback) { const registration = DatabaseSyncTree.getOneByPathEventListener( this.path, eventType, callback, ); if (!registration) { return; } DatabaseSyncTree.removeListenersForRegistrations([`${registration}$cancelled`]); DatabaseSyncTree.removeListenerRegistrations(callback, [registration]); return; } const registrations = DatabaseSyncTree.getRegistrationsByPathEvent(this.path, eventType); DatabaseSyncTree.removeListenersForRegistrations( DatabaseSyncTree.getRegistrationsByPathEvent(this.path, `${eventType}$cancelled`), ); DatabaseSyncTree.removeListenersForRegistrations(registrations); return; } on( eventType: EventType, callback: (data: DataSnapshot, previousChildKey?: string | null) => void, cancelCallbackOrContext?: ((a: Error) => void) | Record | null, context?: Record | null, ): (a: DataSnapshot | null, b?: string | null) => void { if (!eventTypes.includes(eventType)) { throw new Error( `firebase.database().ref().on(*) 'eventType' must be one of ${eventTypes.join(', ')}.`, ); } if (!isFunction(callback)) { throw new Error("firebase.database().ref().on(_, *) 'callback' must be a function."); } if ( !isUndefined(cancelCallbackOrContext) && !isFunction(cancelCallbackOrContext) && !isObject(cancelCallbackOrContext) ) { throw new Error( "firebase.database().ref().on(_, _, *) 'cancelCallbackOrContext' must be a function or object.", ); } if (!isUndefined(context) && !isNull(context) && !isObject(context)) { throw new Error("firebase.database().ref().on(_, _, _, *) 'context' must be an object."); } const queryKey = this._generateQueryKey(); const eventRegistrationKey = this._generateQueryEventKey(eventType); const registrationCancellationKey = `${eventRegistrationKey}$cancelled`; const scopedContext = cancelCallbackOrContext && !isFunction(cancelCallbackOrContext) ? cancelCallbackOrContext : context; DatabaseSyncTree.addRegistration({ eventType, ref: this.ref, path: this.path, key: queryKey, appName: this._database.app.name, dbURL: this._database._customUrlOrRegion, eventRegistrationKey, listener: scopedContext ? callback.bind(scopedContext) : callback, }); if (cancelCallbackOrContext && isFunction(cancelCallbackOrContext)) { DatabaseSyncTree.addRegistration({ ref: this.ref, once: true, path: this.path, key: queryKey, appName: this._database.app.name, dbURL: this._database._customUrlOrRegion, eventType: `${eventType}$cancelled`, eventRegistrationKey: registrationCancellationKey, listener: scopedContext ? cancelCallbackOrContext.bind(scopedContext) : cancelCallbackOrContext, }); } const listenProps: DatabaseListenPropsInternal = { eventType, path: this.path, key: queryKey, modifiers: this._modifiers.toArray(), registration: { eventRegistrationKey, key: queryKey, registrationCancellationKey, }, }; this._database.native.on(listenProps); listeners += 1; return callback as (a: DataSnapshot | null, b?: string | null) => void; } /** * One-shot read backing modular `get()`: on Android and web, the SDKs' single request/response * read (`Query.get()`, web `get()`) instead of the listen -> data -> unlisten exchange * `once('value')` performs. On iOS the native `get` is still the single-event observer; see * `RNFBDatabaseQueryHelper get:`. * * Callers keep `once('value')` semantics, with one exception noted below: * - iOS failures pass straight through (native get already is `once`). * - On Android / web, an error whose code is already a specific `database/*` value (anything * other than `database/unknown`) passes through: Android maps Query.get() permission denials * to the same code `once` gives, and when native get already used `addOnceValueEventListener` * (persistence, logging, keepSynced) its cancellations are those codes too — do not call * `once('value')` again. Only a plain Query.get() failure is rejected as `database/unknown` * (SharedUtils.getExceptionMap); that path still retries as `once('value')`. * - Queries (any orderBy / limit / range modifier) use `once('value')`: `get()` parity for * unindexed queries is unverified. * - `.info/*` paths use `once('value')`: the one-shot reads go to the server tree, not the * client-local `.info` tree. * * The exception: the one-shot read resolves with the server's reply as it was when the read was * sent, where `once('value')` layered this client's pending writes over it. A local write made to * an overlapping path while a `get()` is in flight is therefore not in its result, as with the * web SDK's `get()`. */ _get(): Promise { const modifiers = this._modifiers._copy().toArray(); if (modifiers.length > 0 || INFO_PATH.test(this.path)) { return this.once('value'); } return this._database.native.get(this.path, modifiers).then( result => new DatabaseDataSnapshot(this.ref, result), error => { if (isIOS || isObserverShapedDatabaseError(error)) { return Promise.reject(error); } return this.once('value'); }, ); } once( eventType: EventType, successCallBack?: (a: DataSnapshot, b?: string | null) => any, failureCallbackOrContext?: ((a: Error) => void) | Record | null, context?: Record, ): Promise { if (!eventTypes.includes(eventType)) { throw new Error( `firebase.database().ref().once(*) 'eventType' must be one of ${eventTypes.join(', ')}.`, ); } if (!isUndefined(successCallBack) && !isFunction(successCallBack)) { throw new Error("firebase.database().ref().once(_, *) 'successCallBack' must be a function."); } if ( !isUndefined(failureCallbackOrContext) && !isObject(failureCallbackOrContext) && !isFunction(failureCallbackOrContext) ) { throw new Error( "firebase.database().ref().once(_, _, *) 'failureCallbackOrContext' must be a function or context.", ); } if (!isUndefined(context) && !isObject(context)) { throw new Error( "firebase.database().ref().once(_, _, _, *) 'context' must be a context object.", ); } const modifiers = this._modifiers._copy().toArray(); return this._database.native .once(this.path, modifiers, eventType) .then(result => { let dataSnapshot: DataSnapshot; let previousChildName: string | null | undefined; if (eventType === 'value') { dataSnapshot = new DatabaseDataSnapshot( this.ref, result as ConstructorParameters[1], ); } else { const childResult = result as DatabaseChildSnapshotResultInternal; dataSnapshot = new DatabaseDataSnapshot(this.ref, childResult.snapshot); previousChildName = childResult.previousChildName; } if (isFunction(successCallBack)) { if (isObject(failureCallbackOrContext)) { successCallBack.bind(failureCallbackOrContext)(dataSnapshot, previousChildName); } else if (isObject(context)) { successCallBack.bind(context)(dataSnapshot, previousChildName); } else { successCallBack(dataSnapshot, previousChildName); } } return dataSnapshot; }) .catch(error => { if (isFunction(failureCallbackOrContext)) { failureCallbackOrContext(error); } return Promise.reject(error); }); } orderByChild(path: string): Query { if (!isString(path)) { throw new Error("firebase.database().ref().orderByChild(*) 'path' must be a string value."); } if (pathIsEmpty(path)) { throw new Error( "firebase.database().ref().orderByChild(*) 'path' cannot be empty. Use orderByValue instead.", ); } if (this._modifiers.hasOrderBy()) { throw new Error( "firebase.database().ref().orderByChild(*) You can't combine multiple orderBy calls.", ); } const modifiers = this._modifiers._copy().orderByChild(path); modifiers.validateModifiers('firebase.database().ref().orderByChild()'); return new DatabaseQuery(this._database, this.path, modifiers); } orderByKey(): Query { if (this._modifiers.hasOrderBy()) { throw new Error( "firebase.database().ref().orderByKey() You can't combine multiple orderBy calls.", ); } const modifiers = this._modifiers._copy().orderByKey(); modifiers.validateModifiers('firebase.database().ref().orderByKey()'); return new DatabaseQuery(this._database, this.path, modifiers); } orderByPriority(): Query { if (this._modifiers.hasOrderBy()) { throw new Error( "firebase.database().ref().orderByPriority() You can't combine multiple orderBy calls.", ); } const modifiers = this._modifiers._copy().orderByPriority(); modifiers.validateModifiers('firebase.database().ref().orderByPriority()'); return new DatabaseQuery(this._database, this.path, modifiers); } orderByValue(): Query { if (this._modifiers.hasOrderBy()) { throw new Error( "firebase.database().ref().orderByValue() You can't combine multiple orderBy calls.", ); } const modifiers = this._modifiers._copy().orderByValue(); modifiers.validateModifiers('firebase.database().ref().orderByValue()'); return new DatabaseQuery(this._database, this.path, modifiers); } startAt(value: number | string | boolean | null, key?: string): Query { if (!isNumber(value) && !isString(value) && !isBoolean(value) && !isNull(value)) { throw new Error( "firebase.database().ref().startAt(*) 'value' must be a number, string, boolean or null value.", ); } if (!isUndefined(key) && !isString(key)) { throw new Error( "firebase.database().ref().startAt(_, *) 'key' must be a string value if defined.", ); } if (this._modifiers.hasStartAt()) { throw new Error( 'firebase.database().ref().startAt() Starting point was already set (by another call to startAt or equalTo).', ); } const modifiers = this._modifiers._copy().startAt(value, key); modifiers.validateModifiers('firebase.database().ref().startAt()'); return new DatabaseQuery(this._database, this.path, modifiers); } toJSON(): string { return this.toString(); } toString(): string { return `${this._database._customUrlOrRegion}${pathToUrlEncodedString(this.path)}`; } keepSynced(bool: boolean): Promise { if (!isBoolean(bool)) { throw new Error( "firebase.database().ref().keepSynced(*) 'bool' value must be a boolean value.", ); } return this._database.native.keepSynced( this._generateQueryKey(), this.path, this._modifiers.toArray(), bool, ); } _generateQueryKey(): string { return `$${this._database._customUrlOrRegion}$/${this.path}$${ this._database.app.name }$${this._modifiers.toString()}`; } _generateQueryEventKey(eventType: EventType): string { return `${this._generateQueryKey()}$${listeners}$${eventType}`; } }