Skip to content

Add database@exp API docs #4738

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Apr 6, 2021
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions packages/database/src/core/view/Event.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,10 @@ export interface Event {
toString(): string;
}

/**
* One of the following strings: "value", "child_added", "child_changed",
* "child_removed", or "child_moved."
*/
export type EventType =
| 'value'
| 'child_added'
Expand Down
65 changes: 64 additions & 1 deletion packages/database/src/exp/Database.ts
Original file line number Diff line number Diff line change
Expand Up @@ -262,6 +262,16 @@ export function getDatabase(app: FirebaseApp, url?: string): FirebaseDatabase {
}) as FirebaseDatabase;
}

/**
* Modify the provided instance to communicate with the Realtime Database
* emulator.
*
* <p>Note: This method must be called before performing any other operation.
*
* @param db - The instance to modify.
* @param host - The emulator host (ex: localhost)
* @param port - The emulator port (ex: 8080)
*/
export function useDatabaseEmulator(
db: FirebaseDatabase,
host: string,
Expand All @@ -278,20 +288,73 @@ export function useDatabaseEmulator(
repoManagerApplyEmulatorSettings(db._repo, host, port);
}

/**
* Disconnects from the server (all Database operations will be completed
* offline).
*
* The client automatically maintains a persistent connection to the Database
* server, which will remain active indefinitely and reconnect when
* disconnected. However, the `goOffline()` and `goOnline()` methods may be used
* to control the client connection in cases where a persistent connection is
* undesirable.
*
* While offline, the client will no longer receive data updates from the
* Database. However, all Database operations performed locally will continue to
* immediately fire events, allowing your application to continue behaving
* normally. Additionally, each operation performed locally will automatically
* be queued and retried upon reconnection to the Database server.
*
* To reconnect to the Database and begin receiving remote events, see
* `goOnline()`.
*
* @param db - The instance to disconnect.
*/
export function goOffline(db: FirebaseDatabase): void {
db = getModularInstance(db);
db._checkNotDeleted('goOffline');
repoInterrupt(db._repo);
}

/**
* Reconnects to the server and synchronizes the offline Database state
* with the server state.
*
* This method should be used after disabling the active connection with
* `goOffline()`. Once reconnected, the client will transmit the proper data
* and fire the appropriate events so that your client "catches up"
* automatically.
*
* @param db - The instance to reconnect.
*/
export function goOnline(db: FirebaseDatabase): void {
db = getModularInstance(db);
db._checkNotDeleted('goOnline');
repoResume(db._repo);
}

/**
* Logs debugging information to the console.
*
* @param enabled Enables logging if `true`, disables logging if `false`.
* @param persistent Remembers the logging state between page refreshes if
* `true`.
*/
export function enableLogging(enabled: boolean, persistent?: boolean);

/**
* Logs debugging information to the console.
*
* @param logger A custom logger function to control how things get logged.
* @param persistent Remembers the logging state between page refreshes if
* `true`.
*/
export function enableLogging(
logger?: (message: string) => unknown,
persistent?: boolean
);

export function enableLogging(
logger?: boolean | ((message: string) => unknown),
logger: boolean | ((message: string) => unknown),
persistent?: boolean
): void {
enableLoggingImpl(logger, persistent);
Expand Down
81 changes: 81 additions & 0 deletions packages/database/src/exp/OnDisconnect.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,9 +33,39 @@ import {
validateWritablePath
} from '../core/util/validation';

/**
* The `onDisconnect` class allows you to write or clear data when your client
* disconnects from the Database server. These updates occur whether your
* client disconnects cleanly or not, so you can rely on them to clean up data
* even if a connection is dropped or a client crashes.
*
* The `onDisconnect` class is most commonly used to manage presence in
* applications where it is useful to detect how many clients are connected and
* when other clients disconnect. See {@link
* https://firebase.google.com/docs/database/web/offline-capabilities Enabling
* Offline Capabilities in JavaScript} for more information.
*
* To avoid problems when a connection is dropped before the requests can be
* transferred to the Database server, these functions should be called before
* writing any data.
*
* Note that `onDisconnect` operations are only triggered once. If you want an
* operation to occur each time a disconnect occurs, you'll need to re-establish
* the `onDisconnect` operations each time you reconnect.
*/
export class OnDisconnect {
constructor(private _repo: Repo, private _path: Path) {}

/**
* Cancels all previously queued `onDisconnect()` set or update events for this
* location and all children.
*
* If a write has been queued for this location via a `set()` or `update()` at a
* parent location, the write at this location will be canceled, though writes
* to sibling locations will still occur.
*
* @return Resolves when synchronization to the server is complete.
*/
cancel(): Promise<void> {
const deferred = new Deferred<void>();
repoOnDisconnectCancel(
Expand All @@ -46,6 +76,12 @@ export class OnDisconnect {
return deferred.promise;
}

/**
* Ensures the data at this location is deleted when the client is disconnected
* (due to closing the browser, navigating to a new page, or network issues).
*
* @return Resolves when synchronization to the server is complete.
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think I remember API documenter/extractor insists on @returns instead of @return but if you don't get an error when you run it, never mind.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed. There is no API report yet.

*/
remove(): Promise<void> {
validateWritablePath('OnDisconnect.remove', this._path);
const deferred = new Deferred<void>();
Expand All @@ -58,6 +94,25 @@ export class OnDisconnect {
return deferred.promise;
}

/**
* Ensures the data at this location is set to the specified value when the
* client is disconnected (due to closing the browser, navigating to a new page,
* or network issues).
*
* `set()` is especially useful for implementing "presence" systems, where a
* value should be changed or cleared when a user disconnects so that they
* appear "offline" to other users. See {@link
* https://firebase.google.com/docs/database/web/offline-capabilities Enabling
* Offline Capabilities in JavaScript} for more information.
*
* Note that `onDisconnect` operations are only triggered once. If you want an
* operation to occur each time a disconnect occurs, you'll need to re-establish
* the `onDisconnect` operations each time.
*
* @param value - The value to be written to this location on disconnect (can
* be an object, array, string, number, boolean, or null).
* @return Resolves when synchronization to the Database is complete.
*/
set(value: unknown): Promise<void> {
validateWritablePath('OnDisconnect.set', this._path);
validateFirebaseDataArg('OnDisconnect.set', value, this._path, false);
Expand All @@ -71,6 +126,16 @@ export class OnDisconnect {
return deferred.promise;
}

/**
* Ensures the data at this location is set to the specified value and priority
* when the client is disconnected (due to closing the browser, navigating to a
* new page, or network issues).
*
* @param value - The value to be written to this location on disconnect (can
* be an object, array, string, number, boolean, or null).
* @param priority - The priority to be written (string, number, or null).
* @return Resolves when synchronization to the Database is complete.
*/
setWithPriority(
value: unknown,
priority: number | string | null
Expand All @@ -95,6 +160,22 @@ export class OnDisconnect {
return deferred.promise;
}

/**
* Writes multiple values at this location when the client is disconnected (due
* to closing the browser, navigating to a new page, or network issues).
*
* The `values` argument contains multiple property-value pairs that will be
* written to the Database together. Each child property can either be a simple
* property (for example, "name") or a relative path (for example, "name/first")
* from the current location to the data to update.
*
* As opposed to the `set()` method, `update()` can be use to selectively update
* only the referenced properties at the current location (instead of replacing
* all the child properties at the current location).
*
* @param values Object containing multiple values.
* @return Resolves when synchronization to the Database is complete.
*/
update(values: Indexable): Promise<void> {
validateWritablePath('OnDisconnect.update', this._path);
validateFirebaseMergeDataArg(
Expand Down
91 changes: 91 additions & 0 deletions packages/database/src/exp/Reference.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,25 +19,116 @@ import { QueryContext } from '../core/view/EventRegistration';
* limitations under the License.
*/

/**
* A `Query` sorts and filters the data at a Database location so only a subset
* of the child data is included. This can be used to order a collection of
* data by some attribute (for example, height of dinosaurs) as well as to
* restrict a large list of items (for example, chat messages) down to a number
* suitable for synchronizing to the client. Queries are created by chaining
* together one or more of the filter methods defined here.
*
* Just as with a `Reference`, you can receive data from a `Query` by using the
* `on*()` methods. You will only receive events and `DataSnapshot`s for the
* subset of the data that matches your query.
*
* Read our documentation on {@link
* https://firebase.google.com/docs/database/web/lists-of-data#sorting_and_filtering_data
* Sorting and filtering data} for more information.
*/
export interface Query extends QueryContext {
/** The `Reference` for the `Query`'s location. */
readonly ref: Reference;

/**
* Returns whether or not the current and provided queries represent the same
* location, have the same query parameters, and are from the same instance of
* `FirebaseApp`.
*
* Two `Reference` objects are equivalent if they represent the same location
* and are from the same instance of `FirebaseApp`.
*
* Two `Query` objects are equivalent if they represent the same location,
* have the same query parameters, and are from the same instance of
* `FirebaseApp`. Equivalent queries share the same sort order, limits, and
* starting and ending points.
*
* @param other - The query to compare against.
* @return Whether or not the current and provided queries are equivalent.
*/
isEqual(other: Query | null): boolean;

/**
* Returns a JSON-serializable representation of this object.
*
* @return A JSON-serializable representation of this object.
*/
toJSON(): string;

/**
* Gets the absolute URL for this location.
*
* The `toString()` method returns a URL that is ready to be put into a
* browser, curl command, or a `refFromURL()` call. Since all of those expect
* the URL to be url-encoded, `toString()` returns an encoded URL.
*
* Append '.json' to the returned URL when typed into a browser to download
* JSON-formatted data. If the location is secured (that is, not publicly
* readable), you will get a permission-denied error.
*
* @return The absolute URL for this location.
*/
toString(): string;
}

/**
* A `Reference` represents a specific location in your Database and can be used
* for reading or writing data to that Database location.
*
* You can reference the root or child location in your Database by calling
* `ref()` or `ref("child/path")`.
*
* Writing is done with the `set()` method and reading can be done with the
* `on*()` method. See {@link
* https://firebase.google.com/docs/database/web/read-and-write Read and Write
* Data on the Web}
*/
export interface Reference extends Query {
/**
* The last part of the `Reference`'s path.
*
* For example, `"ada"` is the key for
* `https://<DATABASE_NAME>.firebaseio.com/users/ada`.
*
* The key of a root `Reference` is `null`.
*/
readonly key: string | null;

/**
* The parent location of a `Reference`.
*
* The parent of a root `Reference` is `null`.
*/
readonly parent: Reference | null;

/** The root `Reference` of the Database. */
readonly root: Reference;
}

/**
* A `Promise` that can also act as a `Reference` when returned by
* {@link push}. The reference is available immediately and the Promise resolves
* as the write to the backend completes.
*/
export interface ThenableReference
extends Reference,
Pick<Promise<Reference>, 'then' | 'catch'> {}

/** A callback that can invoked to remove a listener. */
export type Unsubscribe = () => void;

/** An options objects that can be used to customize a listener. */
export interface ListenOptions {
/** Whether to remove the listener after its first invocation. */
readonly onlyOnce?: boolean;
}

Expand Down
Loading