diff --git a/packages/realm/src/ClassHelpers.ts b/packages/realm/src/ClassHelpers.ts index f9ac05fece..ea1fb18032 100644 --- a/packages/realm/src/ClassHelpers.ts +++ b/packages/realm/src/ClassHelpers.ts @@ -28,9 +28,7 @@ import { type ObjectWrapper = (obj: binding.Obj) => (RealmObject & DefaultObject) | null; -/** - * @internal - */ +/** @internal */ export type ClassHelpers = { constructor: RealmObjectConstructor; objectSchema: binding.ObjectSchema; diff --git a/packages/realm/src/ClassMap.ts b/packages/realm/src/ClassMap.ts index 1732bd8799..11b3fe784f 100644 --- a/packages/realm/src/ClassMap.ts +++ b/packages/realm/src/ClassMap.ts @@ -34,9 +34,7 @@ import { setClassHelpers, } from "./internal"; -/** - * @internal - */ +/** @internal */ export class ClassMap { private mapping: Record>; private nameByTableKey: Record; @@ -129,7 +127,7 @@ export class ClassMap { properties, wrapObject(obj) { if (obj.isValid) { - return RealmObject.createWrapper(realm, obj, constructor); + return RealmObject.createWrapper(obj, constructor); } else { return null; } diff --git a/packages/realm/src/Collection.ts b/packages/realm/src/Collection.ts index dc9611bf8f..54770b2522 100644 --- a/packages/realm/src/Collection.ts +++ b/packages/realm/src/Collection.ts @@ -60,21 +60,21 @@ export abstract class Collection< /** * @see {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/keys Array.prototype.keys} - * @returns Iterator with all keys in the collection + * @returns An iterator with all keys in the collection. * @since 0.11.0 */ abstract keys(): Iterable; /** * @see {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/keys Array.prototype.keys} - * @returns Iterator with all values in the collection + * @returns An iterator with all values in the collection. * @since 0.11.0 */ abstract values(): Iterable; /** * @see {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/entries Array.prototype.keys} - * @returns Iterator with all key/value pairs in the collection + * @returns An iterator with all key/value pairs in the collection. * @since 0.11.0 */ abstract entries(): Iterable; @@ -88,7 +88,7 @@ export abstract class Collection< * spread operators, and more. * @see {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol/iterator Symbol.iterator} * and the {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#iterable iterable protocol} - * @returns Iterable of each value in the collection + * @returns An iterable of each value in the collection. * @example * for (let object of collection) { * // do something with each object @@ -106,15 +106,16 @@ export abstract class Collection< /** * Add a listener `callback` which will be called when a **live** collection instance changes. - * @param callback A function to be called when changes occur. - * The callback function is called with two arguments: - * - `collection`: the collection instance that changed, - * - `changes`: a dictionary with keys `insertions`, `newModifications`, `oldModifications` - * and `deletions`, each containing a list of indices in the collection that were - * inserted, updated or deleted respectively. `deletions` and `oldModifications` are - * indices into the collection before the change happened, while `insertions` and - * `newModifications` are indices into the new version of the collection. - * @throws a {@link TypeAssertionError} If `callback` is not a function. + * @param callback - A function to be called when changes occur. + * @param callback.collection - The collection instance that changed, + * @param callback.changes - An object with information about the changes. + * @param callback.changes.insertions - The indices in the collection where objects were inserted. + * @param callback.changes.newModifications - The indices in the collection where objects were modified. + * @param callback.changes.oldModifications - The indices in the collection where objects were modified. + * @param callback.changes.deletions - The indices in the collection where objects were deleted. + * @note `deletions and `oldModifications` report the indices in the collection before the change happened, + * while `insertions` and `newModifications` report the indices into the new version of the collection. + * @throws A {@link TypeAssertionError} if `callback` is not a function. * @example * wines.addListener((collection, changes) => { * // collection === wines @@ -134,8 +135,8 @@ export abstract class Collection< /** * Remove the listener `callback` from the collection instance. - * @param callback Callback function that was previously - * added as a listener through the **addListener** method. + * @param callback - Callback function that was previously + * added as a listener through the {@link Collection.addListener} method. * @throws a {@link TypeAssertionError} If `callback` is not a function. */ removeListener(callback: ChangeCallbackType): void { diff --git a/packages/realm/src/Configuration.ts b/packages/realm/src/Configuration.ts index 91dd94c57d..625dbc8a93 100644 --- a/packages/realm/src/Configuration.ts +++ b/packages/realm/src/Configuration.ts @@ -41,7 +41,7 @@ export type BaseConfiguration = { readOnly?: boolean; fifoFilesFallbackPath?: string; sync?: SyncConfiguration; - /**@internal */ openSyncedRealmLocally?: true; + /** @internal */ openSyncedRealmLocally?: true; shouldCompact?: (totalBytes: number, usedBytes: number) => boolean; deleteRealmIfMigrationNeeded?: boolean; disableFormatUpgrade?: boolean; @@ -59,126 +59,6 @@ export type ConfigurationWithoutSync = BaseConfiguration & { export type Configuration = ConfigurationWithSync | ConfigurationWithoutSync; -// export type PartitionValue = string | number | null | ObjectId | UUID; - -// /** -// * A function which can be called to migrate a Realm from one version of the schema to another. -// */ -// export type MigrationCallback = (oldRealm: Realm, newRealm: Realm) => void; - -// export enum ClientResetModeManualOnly { -// Manual = "manual", -// } - -// export enum ClientResetMode { -// Manual = "manual", -// DiscardLocal = "discardLocal", -// } - -// export type ClientResetBeforeCallback = (localRealm: Realm) => void; -// export type ClientResetAfterCallback = (localRealm: Realm, remoteRealm: Realm) => void; -// export type ClientResetConfiguration = { -// mode: ClientResetModeT; -// clientResetBefore?: ClientResetBeforeCallback; -// clientResetAfter?: ClientResetAfterCallback; -// }; - -// export type BaseSyncConfiguration = { -// user: User; -// customHttpHeaders?: { [header: string]: string }; -// ssl?: SSLConfiguration; -// _sessionStopPolicy?: SessionStopPolicy; -// newRealmFileBehavior?: OpenRealmBehaviorConfiguration; -// existingRealmFileBehavior?: OpenRealmBehaviorConfiguration; -// error?: ErrorCallback; -// }; - -// // We only allow `flexible` to be `true` or `undefined` - `{ flexible: false }` -// // is not allowed. This is because TypeScript cannot discriminate that -// // type correctly with `strictNullChecks` disabled, and there's no real use -// // case for `{ flexible: false }`. -// export type FlexibleSyncConfiguration = BaseSyncConfiguration & { -// flexible: true; -// partitionValue?: never; -// clientReset?: ClientResetConfiguration; -// /** -// * Optional object to configure the setup of an initial set of flexible -// * sync subscriptions to be used when opening the Realm. If this is specified, -// * {@link Realm.open} will not resolve until this set of subscriptions has been -// * fully synchronized with the server. -// * -// * Example: -// * ``` -// * const config: Configuration = { -// * sync: { -// * user, -// * flexible: true, -// * initialSubscriptions: { -// * update: (subs, realm) => { -// * subs.add(realm.objects('Task')); -// * }, -// * rerunOnOpen: true, -// * }, -// * }, -// * // ... rest of config ... -// * }; -// * const realm = await Realm.open(config); -// * -// * // At this point, the Realm will be open with the data for the initial set -// * // subscriptions fully synchronised. -// * ``` -// */ -// initialSubscriptions?: { -// /** -// * Callback called with the {@link Realm} instance to allow you to setup the -// * initial set of subscriptions by calling `realm.subscriptions.update`. -// * See {@link SubscriptionSet.update} for more information. -// */ -// update: (subs: MutableSubscriptionSet, realm: Realm) => void; -// /** -// * If `true`, the {@link update} callback will be rerun every time the Realm is -// * opened (e.g. every time a user opens your app), otherwise (by default) it -// * will only be run if the Realm does not yet exist. -// */ -// rerunOnOpen?: boolean; -// }; -// }; - -// export type PartitionSyncConfiguration = BaseSyncConfiguration & { -// flexible?: never; -// partitionValue: PartitionValue; -// clientReset?: ClientResetConfiguration; -// }; - -// export type SyncConfiguration = FlexibleSyncConfiguration | PartitionSyncConfiguration; - -// export type BaseConfiguration = { -// encryptionKey?: ArrayBuffer | ArrayBufferView | Int8Array; -// schema?: (ObjectConstructor | ObjectSchema)[]; -// schemaVersion?: number; -// shouldCompactOnLaunch?: (totalBytes: number, usedBytes: number) => boolean; -// onFirstOpen?: (realm: Realm) => void; -// path?: string; -// fifoFilesFallbackPath?: string; -// readOnly?: boolean; -// }; - -// export type ConfigurationWithSync = BaseConfiguration & { -// sync: SyncConfiguration; -// migration?: never; -// inMemory?: never; -// deleteRealmIfMigrationNeeded?: never; -// disableFormatUpgrade?: never; -// }; - -// export type ConfigurationWithoutSync = BaseConfiguration & { -// sync?: never; -// migration?: MigrationCallback; -// inMemory?: boolean; -// deleteRealmIfMigrationNeeded?: boolean; -// disableFormatUpgrade?: boolean; -// }; - /** * Validate the fields of a user-provided Realm configuration. * @internal diff --git a/packages/realm/src/Dictionary.ts b/packages/realm/src/Dictionary.ts index 1843e35b33..92991a5953 100644 --- a/packages/realm/src/Dictionary.ts +++ b/packages/realm/src/Dictionary.ts @@ -178,24 +178,26 @@ export class Dictionary extends Collection { yield* this.entries(); } /** * @see {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/keys Array.prototype.keys} - * @returns Iterator with all values in the dictionary - * @since 0.11.0 + * @returns An iterator with all values in the dictionary. + * @since 10.5.0 * @ts-expect-error We're exposing methods in the end-users namespace of keys */ - *keys() { + *keys(): Generator { const snapshot = this[INTERNAL].keys.snapshot(); const size = snapshot.size(); for (let i = 0; i < size; i++) { @@ -206,11 +208,11 @@ export class Dictionary extends Collection { const { fromBinding } = this[HELPERS]; const snapshot = this[INTERNAL].values.snapshot(); const size = snapshot.size(); @@ -221,11 +223,11 @@ export class Dictionary extends Collection { const { fromBinding } = this[HELPERS]; const keys = this[INTERNAL].keys.snapshot(); const values = this[INTERNAL].values.snapshot(); @@ -266,9 +268,9 @@ export class Dictionary extends Collection extends Collection extends OrderedCollection implements Partially }); } - isValid() { + /** + * Checks if this collection has not been deleted and is part of a valid Realm. + * @returns `true` if the collection can be safely accessed. + */ + isValid(): boolean { return this.internal.isValid; } @@ -82,7 +86,7 @@ export class List extends OrderedCollection implements Partially * @param value The value * @internal */ - public set(index: number, value: unknown) { + public set(index: number, value: unknown): void { const { realm, internal, @@ -94,10 +98,16 @@ export class List extends OrderedCollection implements Partially internal.setAny(index, toBinding(value, isEmbedded ? () => [internal.insertEmbedded(index), true] : undefined)); } + /** + * @returns The number of values in the list. + */ get length(): number { return this.internal.size; } + /** + * @throws An {@link Error} as the length property cannot be assigned. + */ set length(value: number) { throw new Error("Cannot assign to read only property 'length'"); } @@ -123,12 +133,11 @@ export class List extends OrderedCollection implements Partially /** * Add one or more values to the _end_ of the list. - * @param items Values to add to the list. - * @throws {TypeError} If a `value` is not of a type which can be stored in - * the list, or if an object being added to the list does not match the {@link ObjectSchema} for the list. - * @throws an {@link AssertionError} If not inside a write transaction. - * @returns A number equal to the new length of - * the list after adding the values. + * @param items - Values to add to the list. + * @throws A {TypeError} if a value is not of a type which can be stored in + * the list, or if an object being added to the list does not match the {@link ObjectSchema} for the list. + * @throws An {@link AssertionError} if not inside a write transaction. + * @returns The new length of the list after adding the values. */ push(...items: T[]): number { assert.inTransaction(this.realm); @@ -152,8 +161,8 @@ export class List extends OrderedCollection implements Partially /** * Remove the **first** value from the list and return it. - * @throws an {@link AssertionError} If not inside a write transaction. - * @returns The first value or undefined if the list is empty. + * @throws An {@link AssertionError} if not inside a write transaction. + * @returns The first value or `undefined` if the list is empty. */ shift(): T | undefined { assert.inTransaction(this.realm); @@ -170,11 +179,11 @@ export class List extends OrderedCollection implements Partially /** * Add one or more values to the _beginning_ of the list. - * @param items Values to add to the list. - * @throws {TypeError} If a `value` is not of a type which can be stored in + * @param items - Values to add to the list. + * @throws A {TypeError} if a value is not of a type which can be stored in * the list, or if an object being added to the list does not match the {@link ObjectSchema} for the list. - * @throws an {@link AssertionError} If not inside a write transaction. - * @returns The new {@link length} of the list after adding the values. + * @throws An {@link AssertionError} if not inside a write transaction. + * @returns The new length of the list after adding the values. */ unshift(...items: T[]): number { assert.inTransaction(this.realm); @@ -195,45 +204,44 @@ export class List extends OrderedCollection implements Partially } /** - * TODO * Changes the contents of the list by removing value and/or inserting new value. * @see {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice Array.prototype.splice} - * @param start The start index. If greater than the length of the list, - * the start index will be set to the length instead. If negative, then the start index - * will be counted from the end of the list (e.g. `list.length - index`). - * @param deleteCount The number of values to remove from the list. - * If not provided, then all values from the start index through the end of - * the list will be removed. + * @param start - The start index. If greater than the length of the list, + * the start index will be set to the length instead. If negative, then the start index + * will be counted from the end of the list (e.g. `list.length - index`). + * @param deleteCount - The number of values to remove from the list. + * If not provided, then all values from the start index through the end of + * the list will be removed. * @returns An array containing the value that were removed from the list. The - * array is empty if no value were removed. + * array is empty if no value were removed. */ splice(start: number, deleteCount?: number): T[]; /** * Changes the contents of the list by removing value and/or inserting new value. * @see {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice Array.prototype.splice} - * @param start The start index. If greater than the length of the list, - * the start index will be set to the length instead. If negative, then the start index - * will be counted from the end of the list (e.g. `list.length - index`). - * @param deleteCount The number of values to remove from the list. - * If not provided, then all values from the start index through the end of - * the list will be removed. - * @param items Values to insert into the list starting at `index`. + * @param start - The start index. If greater than the length of the list, + * the start index will be set to the length instead. If negative, then the start index + * will be counted from the end of the list (e.g. `list.length - index`). + * @param deleteCount - The number of values to remove from the list. + * If not provided, then all values from the start index through the end of + * the list will be removed. + * @param items - Values to insert into the list starting at `index`. * @returns An array containing the value that were removed from the list. The - * array is empty if no value were removed. + * array is empty if no value were removed. */ splice(start: number, deleteCount: number, ...items: T[]): T[]; /** * Changes the contents of the list by removing value and/or inserting new value. * @see {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice Array.prototype.splice} - * @param start The start index. If greater than the length of the list, - * the start index will be set to the length instead. If negative, then the start index - * will be counted from the end of the list (e.g. `list.length - index`). - * @param deleteCount The number of values to remove from the list. - * If not provided, then all values from the start index through the end of - * the list will be removed. - * @param items Values to insert into the list starting at `index`. + * @param start - The start index. If greater than the length of the list, + * the start index will be set to the length instead. If negative, then the start index + * will be counted from the end of the list (e.g. `list.length - index`). + * @param deleteCount - The number of values to remove from the list. + * If not provided, then all values from the start index through the end of + * the list will be removed. + * @param items - Values to insert into the list starting at `index`. * @returns An array containing the value that were removed from the list. The - * array is empty if no value were removed. + * array is empty if no value were removed. */ splice(start: number, deleteCount?: number, ...items: T[]): T[] { // Comments in the code below is copied from https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice @@ -280,11 +288,11 @@ export class List extends OrderedCollection implements Partially /** * Removes the element of the list at the specified index. - * @param index The index of the element to remove. - * @throws an {@link AssertionError} If not inside a write transaction or the input index is less than 0 - * or greater than the size of the list. + * @param index - The index of the element to remove. + * @throws An {@link AssertionError} if not inside a write transaction or the input index is less than 0 + * or greater than or equal to the size of the list. */ - remove(index: number) { + remove(index: number): void { assert.inTransaction(this.realm); assert.number(index, "index"); @@ -296,12 +304,12 @@ export class List extends OrderedCollection implements Partially /** * Moves one element of the list from one index to another. - * @param from The index of the element to move. - * @param to The destination index of the element. - * @throws an {@link AssertionError} If not inside a write transaction or if any of the input indexes - * is less than 0 or greater than the size of the list. + * @param from - The index of the element to move. + * @param to - The destination index of the element. + * @throws An {@link AssertionError} if not inside a write transaction or if any of the input indexes + * is less than 0 or greater than or equal to the size of the list. */ - move(from: number, to: number) { + move(from: number, to: number): void { assert.inTransaction(this.realm); assert.number(from, "from"); assert.number(to, "to"); @@ -315,12 +323,12 @@ export class List extends OrderedCollection implements Partially /** * Swaps the positions of the elements of the list at two indexes. - * @param index1 The index of the first element. - * @param index2 The index of the second element. - * @throws an {@link AssertionError} If not inside a write transaction or if any of the input indexes - * is less than 0 or greater than the size of the list. + * @param index1 - The index of the first element. + * @param index2 - The index of the second element. + * @throws An {@link AssertionError} if not inside a write transaction or if any of the input indexes + * is less than 0 or greater than or equal to the size of the list. */ - swap(index1: number, index2: number) { + swap(index1: number, index2: number): void { assert.inTransaction(this.realm); assert.number(index1, "index1"); assert.number(index2, "index2"); diff --git a/packages/realm/src/Logger.ts b/packages/realm/src/Logger.ts index 9dcdea0372..5f753dde7b 100644 --- a/packages/realm/src/Logger.ts +++ b/packages/realm/src/Logger.ts @@ -34,9 +34,9 @@ export enum NumericLogLevel { /** * A callback passed to `Realm.App.Sync.setLogger` when instrumenting the Atlas Device Sync client with a custom logger. - * @param {number} level The level of the log entry between 0 and 8 inclusively. + * @param level - The level of the log entry between 0 and 8 inclusively. * Use this as an index into `['all', 'trace', 'debug', 'detail', 'info', 'warn', 'error', 'fatal', 'off']` to get the name of the level. - * @param {string} message The message of the log entry. + * @param message - The message of the log entry. */ export type Logger = (level: NumericLogLevel, message: string) => void; diff --git a/packages/realm/src/Object.ts b/packages/realm/src/Object.ts index deeb0cc2bc..77519321e2 100644 --- a/packages/realm/src/Object.ts +++ b/packages/realm/src/Object.ts @@ -40,9 +40,27 @@ import { getTypeName, } from "./internal"; +/** + * The update mode to use when creating an object that already exists. + */ export enum UpdateMode { + /** + * Objects are only created. If an existing object exists, an exception is thrown. + */ Never = "never", + /** + * If an existing object exists, only properties where the value has actually + * changed will be updated. This improves notifications and server side + * performance but also have implications for how changes across devices are + * merged. For most use cases, the behavior will match the intuitive behavior + * of how changes should be merged, but if updating an entire object is + * considered an atomic operation, this mode should not be used. + */ Modified = "modified", + /** + * If an existing object is found, all properties provided will be updated, + * any other properties will remain unchanged. + */ All = "all", } @@ -90,16 +108,38 @@ const PROXY_HANDLER: ProxyHandler> = { /** * Base class for a Realm Object. * @example - * To define a class `Person` which requires the `name` and `age` properties to be - * specified when it is being constructed, using the Realm Babel plugin to allow - * Typescript-only model definitions (otherwise it would require a `static` schema): + * To define a class `Person` with required `name` and `age` + * properties, define a `static schema`: + * ``` + * class Person extends Realm.Object { + * _id!: Realm.BSON.ObjectId; + * name!: string; + * age!: number; + * static schema: Realm.ObjectSchema = { + * name: "Person", + * primaryKey: "_id", + * properties: { + * _id: "objectId", + * name: "string", + * age: "int", + * }, + * }; + * } + * ``` + * @example + * If using the [@realm/babel-plugin](https://www.npmjs.com/package/@realm/babel-plugin): + * To define a class `Person` with required `name` and `age` properties, they would + * need to be specified in the type argument when it is being constructed to allow + * Typescript-only model definitions: * ``` * class Person extends Realm.Object { * _id = new Realm.Types.ObjectId(); - * name: string; + * name: Realm.Types.String; * age: Realm.Types.Int; + * static primaryKey = "_id"; * } * ``` + * @see {@link ObjectSchema} * @typeParam `T` - The type of this class (e.g. if your class is `Person`, * `T` should also be `Person` - this duplication is required due to how * TypeScript works) @@ -118,17 +158,17 @@ export class RealmObject( - realm: Realm, - internal: binding.Obj, - constructor: Constructor, - ): RealmObject & T { + public static createWrapper(internal: binding.Obj, constructor: Constructor): RealmObject & T { const result = Object.create(constructor.prototype); result[INTERNAL] = internal; // Initializing INTERNAL_LISTENERS here rather than letting it just be implicitly undefined since JS engines @@ -273,8 +309,8 @@ export class RealmObject) { return realm.create(this.constructor as RealmObjectConstructor, values) as unknown as this; @@ -366,7 +402,6 @@ export class RealmObject { return this[REALM].getClassHelpers(this).canonicalObjectSchema as CanonicalObjectSchema; @@ -383,11 +417,10 @@ export class RealmObject(objectType: string, propertyName: string): Results & T>; linkingObjects(objectType: Constructor, propertyName: string): Results; @@ -412,7 +445,6 @@ export class RealmObject { * // obj === wine @@ -453,7 +484,6 @@ export class RealmObject): void { assert.function(callback); @@ -464,10 +494,9 @@ export class RealmObject): void { assert.function(callback); @@ -476,20 +505,18 @@ export class RealmObject & T): void { + removeAllListeners(): void { // Note: if the INTERNAL_LISTENERS field hasn't been initialized, then we have no listeners to remove. this[INTERNAL_LISTENERS]?.removeAllListeners(); } /** * Get underlying type of a property value. - * @param propertyName The name of the property to retrieve the type of. - * @throws an {@link Error} If property does not exist. + * @param propertyName - The name of the property to retrieve the type of. + * @throws An {@link Error} if property does not exist. * @returns Underlying type of the property value. - * @since 10.8.0 */ getPropertyType(propertyName: string): string { const { properties } = this[REALM].getClassHelpers(this); @@ -535,6 +562,6 @@ export class RealmObject = { /** * An {@link OrderedCollection} is a homogenous sequence of values of any of the types * that can be stored as properties of Realm objects. It can be - * accessed in any of the ways that a normal Javascript Array can, including + * accessed in any of the ways that a normal JavaScript Array can, including * subscripting, enumerating with `for-of` and so on. + * @see {@link https://mdn.io/Array | Array} */ export abstract class OrderedCollection extends Collection> @@ -185,9 +186,9 @@ export abstract class OrderedCollection binding.MixedArg; /** - * Get an element of the ordered collection by index - * @param index The index - * @returns The element + * Get an element of the ordered collection by index. + * @param index - The index. + * @returns The element. * @internal */ public get(index: number): T { @@ -195,9 +196,9 @@ export abstract class OrderedCollection; - /** - * @internal - */ + /** @internal */ toJSON(_?: string, cache = new JSONCacheMap()): Array { return this.map((item, index) => { if (item instanceof RealmObject) { @@ -226,9 +225,10 @@ export abstract class OrderedCollection { const size = this.results.size(); for (let i = 0; i < size; i++) { yield i; @@ -236,9 +236,10 @@ export abstract class OrderedCollection { const snapshot = this.results.snapshot(); const { get, fromBinding } = this.helpers; for (const i of this.keys()) { @@ -247,9 +248,10 @@ export abstract class OrderedCollection { const { get, fromBinding } = this.helpers; const snapshot = this.results.snapshot(); const size = snapshot.size(); @@ -261,7 +263,7 @@ export abstract class OrderedCollection[]): T[]; /** - * @see {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/concat Array.prototype.concat} + * @see {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/concat | Array.prototype.concat()} + * @param items - Arrays and/or values to concatenate into a new array. + * @returns A new array with the results of calling a provided function on every element in this array. */ concat(...items: (T | ConcatArray)[]): T[]; concat(...items: any[]): T[] { return [...this].concat(...items); } /** - * @see {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/join Array.prototype.join} + * @see {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/join | Array.prototype.join()} + * @params separator - A string used to separate one element of the collection from the next in the resulting String. + * @returns A string representing the elements of the collection. */ join(separator?: string): string { return [...this].join(separator); } /** - * @see {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice Array.prototype.slice} + * @see {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice | Array.prototype.slice()} + * @params start - Zero-based index at which to begin extraction. + * @params end - Zero-based index at which to end extraction. It extracts up to but not including `end`. + * @returns A new array containing the elements between the start and end indices. */ slice(start?: number, end?: number): T[] { return [...this].slice(start, end); } /** - * @see {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf Array.prototype.indexOf} + * @see {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf | Array.prototype.indexOf()} + * @params searchElement - Element to locate in the collection. + * @params fromIndex - The collection index at which to begin the search. If omitted, the search starts at index 0. + * @note `fromIndex` is currently not supported. So all searches start at index 0. + * @returns The first index at which a given element can be found in the collection, or -1 if it is not present. */ indexOf(searchElement: T, fromIndex?: number): number { assert(typeof fromIndex === "undefined", "The second fromIndex argument is not yet supported"); @@ -340,67 +358,132 @@ export abstract class OrderedCollection( predicate: (value: T, index: number, array: readonly T[]) => value is S, thisArg?: any, ): this is readonly S[]; /** - * @see {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/every Array.prototype.every} + * @see {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/every | Array.prototype.every()} + * @params predicate - A function to test for each element. + * @params predicate.value - The current element being processed in the collection. + * @params predicate.index - The index of the current element being processed in the collection. + * @params predicate.array - The collection `every` was called upon. + * @params thisArg - An object to which the `this` keyword can refer in the predicate function. If `thisArg` is omitted, `undefined` is used as the `this` value. + * @returns `true` if the callback function returns a truthy value for every collection element; otherwise, `false`. */ every(predicate: (value: T, index: number, array: readonly T[]) => unknown, thisArg?: any): boolean; every(predicate: any, thisArg?: any): boolean { return [...this].every(predicate, thisArg); } /** - * @see {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/some Array.prototype.some} + * @see {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/some | Array.prototype.some()} + * @params predicate - A function to test for each element. + * @params predicate.value - The current element being processed in the collection. + * @params predicate.index - The index of the current element being processed in the collection. + * @params predicate.array - The collection `every` was called upon. + * @params thisArg - An object to which the `this` keyword can refer in the predicate function. If `thisArg` is omitted, `undefined` is used as the `this` value. + * @returns `true` if the callback function returns a truthy value for any collection element; otherwise, `false`. */ some(predicate: (value: T, index: number, array: readonly T[]) => unknown, thisArg?: any): boolean { return [...this].some(predicate, thisArg); } /** - * @see {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach Array.prototype.forEach} + * @see {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach | Array.prototype.forEach()} + * @params callbackfn - A function that accepts up to three arguments. `forEach` calls the callbackfn function one time for each element in the collection. + * @params callbackfn.value - The current element being processed in the collection. + * @params callbackfn.index - The index of the current element being processed in the collection. + * @params callbackfn.array - The collection `forEach` was called upon. + * @params thisArg - An object to which the `this` keyword can refer in the `callbackfn` function. If `thisArg` is omitted, `undefined` is used as the `this` value. */ forEach(callbackfn: (value: T, index: number, array: readonly T[]) => void, thisArg?: any): void { return [...this].forEach(callbackfn, thisArg); } /** - * @see {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map Array.prototype.map} + * @see {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map | Array.prototype.map()} + * @params callbackfn - A function that accepts up to three arguments. The `map` method calls the `callbackfn` function one time for each element in the collection. + * @params callbackfn.value - The current element being processed in the collection. + * @params callbackfn.index - The index of the current element being processed in the collection. + * @params callbackfn.array - The collection `map` was called upon. + * @params thisArg - An object to which the `this` keyword can refer in the `callbackfn` function. If `thisArg` is omitted, `undefined` is used as the `this` value. + * @returns A new array containing the results of calling the `callbackfn` function on each element in the collection. */ map(callbackfn: (value: T, index: number, array: readonly T[]) => U, thisArg?: any): U[] { return [...this].map(callbackfn, thisArg); } /** - * @see {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter Array.prototype.filter} + * @see {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter | Array.prototype.filter()} + * @params predicate - A function that accepts up to three arguments. The `filter` method calls the `predicate` function one time for each element in the collection. + * @params predicate.value - The current element being processed in the collection. + * @params predicate.index - The index of the current element being processed in the collection. + * @params predicate.array - The collection `filter` was called upon. + * @params thisArg - An object to which the `this` keyword can refer in the `predicate` function. If `thisArg` is omitted, `undefined` is used as the `this` value. + * @returns A new array containing the elements of the collection for which the `predicate` function returned `true`. */ filter(predicate: (value: T, index: number, array: readonly T[]) => value is S, thisArg?: any): S[]; /** - * @see {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter Array.prototype.filter} + * @see {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter | Array.prototype.filter()} + * @params predicate - A function that accepts up to three arguments. The `filter` method calls the `predicate` function one time for each element in the collection. + * @params predicate.value - The current element being processed in the collection. + * @params predicate.index - The index of the current element being processed in the collection. + * @params predicate.array - The collection `filter` was called upon. + * @params thisArg - An object to which the `this` keyword can refer in the `predicate` function. If `thisArg` is omitted, `undefined` is used as the `this` value. + * @returns A new array containing the elements of the collection for which the `predicate` function returned `true`. */ filter(predicate: (value: T, index: number, array: readonly T[]) => unknown, thisArg?: any): T[]; filter(predicate: any, thisArg?: any): T[] | S[] { return [...this].filter(predicate, thisArg); } /** - * @see {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce Array.prototype.reduce} + * @see {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce | Array.prototype.reduce()} + * @params callbackfn - A function that accepts up to four arguments. The `reduce` method calls the `callbackfn` function one time for each element in the collection. + * @params callbackfn.previousValue - The value previously returned in the last invocation of the `callbackfn` function, or `initialValue`, if supplied. (See below.) + * @params callbackfn.currentValue - The current element being processed in the collection. + * @params callbackfn.currentIndex - The index of the current element being processed in the collection. + * @params callbackfn.array - The collection `reduce` was called upon. + * @params initialValue - If `initialValue` is specified, it is used as the initial value to start the accumulation. The first call to the `callbackfn` function provides this value as an argument instead of an element value. + * @returns The value that results from the reduction. */ reduce(callbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: readonly T[]) => T): T; /** - * @see {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce Array.prototype.reduce} + * @see {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce | Array.prototype.reduce()} + * @params callbackfn - A function that accepts up to four arguments. The `reduce` method calls the `callbackfn` function one time for each element in the collection. + * @params callbackfn.previousValue - The value previously returned in the last invocation of the `callbackfn` function, or `initialValue`, if supplied. (See below.) + * @params callbackfn.currentValue - The current element being processed in the collection. + * @params callbackfn.currentIndex - The index of the current element being processed in the collection. + * @params callbackfn.array - The collection `reduce` was called upon. + * @params initialValue - If `initialValue` is specified, it is used as the initial value to start the accumulation. The first call to the `callbackfn` function provides this value as an argument instead of an element value. + * @returns The value that results from the reduction. */ reduce( callbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: readonly T[]) => T, initialValue: T, ): T; /** - * @see {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce Array.prototype.reduce} + * @see {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce | Array.prototype.reduce()} + * @params callbackfn - A function that accepts up to four arguments. The `reduce` method calls the `callbackfn` function one time for each element in the collection. + * @params callbackfn.previousValue - The value previously returned in the last invocation of the `callbackfn` function, or `initialValue`, if supplied. (See below.) + * @params callbackfn.currentValue - The current element being processed in the collection. + * @params callbackfn.currentIndex - The index of the current element being processed in the collection. + * @params callbackfn.array - The collection `reduce` was called upon. + * @params initialValue - If `initialValue` is specified, it is used as the initial value to start the accumulation. The first call to the `callbackfn` function provides this value as an argument instead of an element value. + * @returns The value that results from the reduction. */ reduce( callbackfn: (previousValue: U, currentValue: T, currentIndex: number, array: readonly T[]) => U, @@ -410,18 +493,39 @@ export abstract class OrderedCollection T): T; /** - * @see {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduceRight Array.prototype.reduceRight} + * @see {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduceRight | Array.prototype.reduceRight()} + * @params callbackfn - A function that accepts up to four arguments. The `reduceRight` method calls the `callbackfn` function one time for each element in the collection. + * @params callbackfn.previousValue - The value previously returned in the last invocation of the `callbackfn` function, or `initialValue`, if supplied. (See below.) + * @params callbackfn.currentValue - The current element being processed in the collection. + * @params callbackfn.currentIndex - The index of the current element being processed in the collection. + * @params callbackfn.array - The collection `reduceRight` was called upon. + * @params initialValue - If `initialValue` is specified, it is used as the initial value to start the accumulation. The first call to the `callbackfn` function provides this value as an argument instead of an element value. + * @returns The value that results from the reduction. */ reduceRight( callbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: readonly T[]) => T, initialValue: T, ): T; /** - * @see {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduceRight Array.prototype.reduceRight} + * @see {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduceRight | Array.prototype.reduceRight()} + * @params callbackfn - A function that accepts up to four arguments. The `reduceRight` method calls the `callbackfn` function one time for each element in the collection. + * @params callbackfn.previousValue - The value previously returned in the last invocation of the `callbackfn` function, or `initialValue`, if supplied. (See below.) + * @params callbackfn.currentValue - The current element being processed in the collection. + * @params callbackfn.currentIndex - The index of the current element being processed in the collection. + * @params callbackfn.array - The collection `reduceRight` was called upon. + * @params initialValue - If `initialValue` is specified, it is used as the initial value to start the accumulation. The first call to the `callbackfn` function provides this value as an argument instead of an element value. + * @returns The value that results from the reduction. */ reduceRight( callbackfn: (previousValue: U, currentValue: T, currentIndex: number, array: readonly T[]) => U, @@ -432,34 +536,62 @@ export abstract class OrderedCollection( predicate: (this: void, value: T, index: number, obj: T[]) => value is S, thisArg?: any, ): S | undefined; /** - * @see {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find Array.prototype.find} + * @see {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find | Array.prototype.find()} + * @params predicate - A function that accepts up to three arguments. The `find` method calls the `predicate` function one time for each element in the collection. + * @params predicate.value - The value of the element. + * @params predicate.index - The index of the element. + * @params predicate.obj - The object being traversed. + * @params thisArg - An object to which the `this` keyword can refer in the `predicate` function. If `thisArg` is omitted, `undefined` is used as the `this` value. + * @returns The value of the first element in the array that satisfies the provided testing function. Otherwise, `undefined` is returned. */ find(predicate: (value: T, index: number, obj: T[]) => unknown, thisArg?: any): T | undefined; find(predicate: (value: T, index: number, obj: T[]) => boolean, thisArg?: any): T | undefined { return [...this].find(predicate, thisArg); } /** - * @see {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/findIndex Array.prototype.findIndex} + * @see {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/findIndex | Array.prototype.findIndex()} + * @params predicate - A function that accepts up to three arguments. The `findIndex` method calls the `predicate` function one time for each element in the collection. + * @params predicate.value - The value of the element. + * @params predicate.index - The index of the element. + * @params predicate.obj - The object being traversed. + * @params thisArg - An object to which the `this` keyword can refer in the `predicate` function. If `thisArg` is omitted, `undefined` is used as the `this` value. + * @returns The index of the first element in the array that satisfies the provided testing function. Otherwise, -1 is returned. */ findIndex(predicate: (value: T, index: number, obj: readonly T[]) => unknown, thisArg?: any): number { return [...this].findIndex(predicate, thisArg); } // TODO: Implement support for RealmObjects, by comparing their #objectKey values /** - * @see {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes Array.prototype.includes} + * @see {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes | Array.prototype.includes()} + * @params searchElement - The element to search for. + * @params fromIndex - The position in this array at which to begin searching for `searchElement`. A negative value searches from the index of array.length + fromIndex by asc. + * @note `fromIndex` is currently not supported. So all searches start at index 0. + * @returns `true` if the `searchElement` is found in the array; otherwise, `false`. */ includes(searchElement: T, fromIndex?: number): boolean { return this.indexOf(searchElement, fromIndex) !== -1; } /** - * @see {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/flatMap Array.prototype.flatMap} + * @see {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/flatMap | Array.prototype.flatMap()} + * @params callback - Function that produces an element of the new Array, taking three arguments: + * @params callback.currentValue - The current element being processed in the array. + * @params callback.index - The index of the current element being processed in the array. + * @params callback.array - The array `flatMap` was called upon. + * @params thisArg - Value to use as this when executing callback. + * @returns A new array with each element being the result of the callback function and flattened to a depth of 1. */ flatMap( callback: (this: This, value: T, index: number, array: T[]) => U | readonly U[], @@ -468,27 +600,38 @@ export abstract class OrderedCollection(this: A, depth?: D): FlatArray[]; flat(): FlatArray[] { throw new Error("Method not implemented."); } /** - * @see {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/at Array.prototype.at} + * @see {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/at | Array.prototype.at()} + * @params index - The index of the element to return from the array. If the index is a negative number, the element at `array.length + index` is returned. + * @returns The element at the given index in the array; `undefined` if there is no element at the given index. */ - at(index: number) { + at(index: number): T | undefined { return [...this].at(index); } /* eslint-enable @typescript-eslint/no-explicit-any */ + /** + * @returns An iterator that iterates over all the values in the collection. + */ [Symbol.iterator](): IterableIterator { return this.values(); } // Other methods + // TODO: Implement this method + /** + * @returns A string describing the filters applied to this collection. + */ description(): string { throw new Error("Method not implemented."); } @@ -496,7 +639,6 @@ export abstract class OrderedCollection; @@ -667,8 +804,8 @@ export abstract class OrderedCollection; @@ -686,8 +823,8 @@ export abstract class OrderedCollection; diff --git a/packages/realm/src/Realm.ts b/packages/realm/src/Realm.ts index f92ffc736d..fb63eca87a 100644 --- a/packages/realm/src/Realm.ts +++ b/packages/realm/src/Realm.ts @@ -211,8 +211,8 @@ export type RealmEventName = "change" | "schema" | "beforenotify"; /** * Asserts the event passed as string is a valid RealmEvent value. - * @throws {@link TypeAssertionError} If an unexpected name is passed via {@link name}. - * @param name The name of the event. + * @throws A {@link TypeAssertionError} if an unexpected name is passed via {@link name}. + * @param name - The name of the event. * @internal */ function assertRealmEvent(name: RealmEventName): asserts name is RealmEvent { @@ -275,7 +275,7 @@ export class Realm { /** * Sets the log level. - * @param level The log level to be used by the logger. The default value is `info`. + * @param level - The log level to be used by the logger. The default value is `info`. * @note The log level can be changed during the lifetime of the application. * @since v12.0.0 */ @@ -286,7 +286,7 @@ export class Realm { /** * Sets the logger callback. - * @param loggerCallback The callback invoked by the logger. The default callback uses `console.log`, `console.warn` and `console.error`, depending on the level of the message. + * @param loggerCallback - The callback invoked by the logger. The default callback uses `console.log`, `console.warn` and `console.error`, depending on the level of the message. * @note The logger callback needs to be setup before opening the first realm. * @since v12.0.0 */ @@ -323,8 +323,8 @@ export class Realm { /** * Delete the Realm file for the given configuration. - * @param config The configuration for the Realm - * @throws an {@link Error} If anything in the provided {@link config} is invalid. + * @param config - The configuration for the Realm being deleted. + * @throws An {@link Error} if anything in the provided {@link config} is invalid. */ public static deleteFile(config: Configuration): void { validateConfiguration(config); @@ -338,8 +338,8 @@ export class Realm { /** * Checks if the Realm already exists on disk. - * @param arg The configuration for the Realm or the path to it. - * @throws an {@link Error} If anything in the provided {@link config} is invalid. + * @param arg - The configuration for the Realm or the path to it. + * @throws An {@link Error} if anything in the provided {@link config} is invalid. * @returns `true` if the Realm exists on the device, `false` if not. */ public static exists(arg: Configuration | string = {}): boolean { @@ -354,9 +354,9 @@ export class Realm { * synchronized before it is available. * In the case of query-based sync, {@link Configuration.scheme | config.schema} is required. An exception will be * thrown if {@link Configuration.scheme | config.schema} is not defined. - * @param arg The configuration for the Realm or the path to it. + * @param arg - The configuration for the Realm or the path to it. * @returns A promise that will be resolved with the Realm instance when it's available. - * @throws an {@link Error} If anything in the provided {@link arg} is invalid. + * @throws An {@link Error} if anything in the provided {@link arg} is invalid. */ public static open(arg: Configuration | string = {}): ProgressRealmPromise { const config = typeof arg === "string" ? { path: arg } : arg; @@ -365,12 +365,10 @@ export class Realm { /** * Get the current schema version of the Realm at the given path. - * @param path The path to the file where the - * Realm database is stored. - * @param encryptionKey Required only when - * accessing encrypted Realms. - * @throws an {@link Error} If passing an invalid or non-matching encryption key. - * @returns Version of the schema, or `-1` if no Realm exists at {@link path}. + * @param path - The path to the file where the Realm database is stored. + * @param encryptionKey - Required only when accessing encrypted Realms. + * @throws An {@link Error} if passing an invalid or non-matching encryption key. + * @returns Version of the schema as an integer, or `-1` if no Realm exists at {@link path}. */ public static schemaVersion(path: string, encryptionKey?: ArrayBuffer | ArrayBufferView): number { const config: Configuration = { path }; @@ -387,7 +385,7 @@ export class Realm { * and all required fields have the default value for the given data type, either the value * set by the default property in the schema or the default value for the datatype if the schema * doesn't specify one, i.e. 0, false and "". - * @param objectSchema Schema describing the object that should be created. + * @param objectSchema - Schema describing the object that should be created. */ public static createTemplateObject>(objectSchema: ObjectSchema): T { validateObjectSchema(objectSchema); @@ -441,8 +439,8 @@ export class Realm { * overwritten, so this can safely be called multiple times. * * This should be called before opening the Realm, in order to move the bundled Realm - * files into a place where they can be written to, for example: - * + * files into a place where they can be written to. + * @example * ``` * // Given a bundled file, example.realm, this will copy example.realm (and any other .realm files) * // from the app bundle into the app's documents directory. If the file already exists, it will @@ -608,14 +606,14 @@ export class Realm { /** * Create a new {@link Realm} instance, at the default path. - * @throws an {@link Error} When an incompatible synced Realm is opened. + * @throws An {@link Error} when an incompatible synced Realm is opened. */ constructor(); /** * Create a new {@link Realm} instance at the provided {@link path}. - * @param path Required when first creating the Realm. - * @throws an {@link Error} If the Realm cannot be opened at the provided {@link path}. - * @throws an {@link Error} When an incompatible synced Realm is opened. + * @param path - Required when first creating the Realm. + * @throws An {@link Error} if the Realm cannot be opened at the provided {@link path}. + * @throws An {@link Error} when an incompatible synced Realm is opened. */ constructor(path: string); /** @@ -628,9 +626,9 @@ export class Realm { * migrated to use the new schema. * In the case of query-based sync, {@link Configuration.schema | config.schema} is required. An exception will be * thrown if {@link Configuration.schema | config.schema} is not defined. - * @param config Required when first creating the Realm. - * @throws an {@link Error} If anything in the provided {@link config} is invalid. - * @throws an {@link Error} When an incompatible synced Realm is opened. + * @param config - Required when first creating the Realm. + * @throws An {@link Error} if anything in the provided {@link config} is invalid. + * @throws An {@link Error} when an incompatible synced Realm is opened. */ constructor(config: Configuration); /** @internal */ @@ -701,6 +699,7 @@ export class Realm { /** * Indicates if this Realm contains any objects. + * @returns `true` if empty, `false` otherwise. * @readonly * @since 1.10.0 */ @@ -710,6 +709,7 @@ export class Realm { /** * The path to the file where this Realm is stored. + * @returns A string containing the path to the file where this Realm is stored. * @readonly * @since 0.12.0 */ @@ -719,6 +719,7 @@ export class Realm { /** * Indicates if this Realm was opened as read-only. + * @returns `true` if this Realm is read-only, `false` otherwise. * @readonly * @since 0.12.0 */ @@ -728,6 +729,7 @@ export class Realm { /** * Indicates if this Realm was opened in-memory. + * @returns `true` if this Realm is in-memory, `false` otherwise. * @readonly */ get isInMemory(): boolean { @@ -736,6 +738,7 @@ export class Realm { /** * A normalized representation of the schema provided in the {@link Configuration} when this Realm was constructed. + * @returns An array of {@link CanonicalObjectSchema} describing all objects in this Realm. * @readonly * @since 0.12.0 */ @@ -756,6 +759,7 @@ export class Realm { /** * The current schema version of the Realm. + * @returns The schema version of this Realm, as a `number`. * @readonly * @since 0.12.0 */ @@ -765,6 +769,7 @@ export class Realm { /** * Indicates if this Realm is in a write transaction. + * @returns `true` if in a write transaction, `false` otherwise. * @readonly * @since 1.10.3 */ @@ -775,6 +780,7 @@ export class Realm { /** * Indicates if this Realm has been closed. + * @returns `true` if closed, `false` otherwise. * @readonly * @since 2.1.0 */ @@ -785,7 +791,8 @@ export class Realm { /** * The latest set of flexible sync subscriptions. - * @throws an {@link Error} If flexible sync is not enabled for this app. + * @returns A {@link SubscriptionSet} object. + * @throws An {@link Error} if flexible sync is not enabled for this app. */ get subscriptions(): SubscriptionSet { const { syncConfig } = this.internal.config; @@ -819,19 +826,10 @@ export class Realm { /** * Create a new {@link RealmObject} of the given type and with the specified properties. For objects marked asymmetric, * `undefined` is returned. The API for asymmetric objects is subject to changes in the future. - * @param type The type of Realm object to create. - * @param values Property values for all required properties without a - * default value. - * @param mode Optional update mode. It can be one of the following values - * - UpdateMode.Never: Objects are only created. If an existing object exists, an exception is thrown. This is the - * default value. - * - UpdateMode.All: If an existing object is found, all properties provided will be updated, any other properties will - * remain unchanged. - * - UpdateMode.Modified: If an existing object exists, only properties where the value has actually changed will be - * updated. This improves notifications and server side performance but also have implications for how changes - * across devices are merged. For most use cases, the behavior will match the intuitive behavior of how - * changes should be merged, but if updating an entire object is considered an atomic operation, this mode - * should not be used. + * @param type - The type of Realm object to create. + * @param values - Property values for all required properties without a + * default value. + * @param mode Optional update mode. The default is `UpdateMode.Never`. * @returns A {@link RealmObject} or `undefined` if the object is asymmetric. */ create( @@ -848,7 +846,7 @@ export class Realm { type: string | Constructor, values: DefaultObject, mode: UpdateMode | boolean = UpdateMode.Never, - ) { + ): RealmObject | undefined { // Supporting a boolean overload for mode if (mode === true) { mode = UpdateMode.All; @@ -871,6 +869,7 @@ export class Realm { /** * Deletes the provided Realm object, or each one inside the provided collection. + * @param subject - The Realm object to delete, or a collection containing multiple Realm objects to delete. */ delete(subject: AnyRealmObject | AnyRealmObject[] | List | Results): void { assert.inTransaction(this, "Can only delete objects within a transaction."); @@ -905,7 +904,7 @@ export class Realm { /** * Deletes a Realm model, including all of its objects. * If called outside a migration function, {@link schema} and {@link schemaVersion} are updated. - * @param name The model name + * @param name - The model name. */ deleteModel(name: string): void { assert.inTransaction(this, "Can only delete objects within a transaction."); @@ -935,10 +934,10 @@ export class Realm { /** * Searches for a Realm object by its primary key. - * @param type The type of Realm object to search for. - * @param primaryKey The primary key value of the object to search for. - * @throws an {@link Error} If type passed into this method is invalid, or if the object type did - * not have a {@link primaryKey} specified in the schema, or if it was marked asymmetric. + * @param type - The type of Realm object to search for. + * @param primaryKey - The primary key value of the object to search for. + * @throws An {@link Error} if type passed into this method is invalid, or if the object type did + * not have a {@link primaryKey} specified in the schema, or if it was marked asymmetric. * @returns A {@link RealmObject} or `null` if no object is found. * @since 0.14.0 */ @@ -975,9 +974,9 @@ export class Realm { /** * Returns all objects of the given {@link type} in the Realm. - * @param type The type of Realm object to search for. - * @param objectKey The object key of the Realm object to search for. - * @throws an {@link Error} If type passed into this method is invalid or if the type is marked embedded or asymmetric. + * @param type - The type of Realm object to search for. + * @param objectKey - The object key of the Realm object to search for. + * @throws An {@link Error} if type passed into this method is invalid or if the type is marked embedded or asymmetric. * @returns A {@link RealmObject} or `undefined` if the object key is not found. * @internal */ @@ -1010,8 +1009,8 @@ export class Realm { /** * Returns all objects of the given {@link type} in the Realm. - * @param type The type of Realm objects to retrieve. - * @throws an {@link Error} If type passed into this method is invalid or if the type is marked embedded or asymmetric. + * @param type - The type of Realm objects to retrieve. + * @throws An {@link Error} if type passed into this method is invalid or if the type is marked embedded or asymmetric. * @returns Results that will live-update as objects are created, modified, and destroyed. */ objects(type: string): Results & T>; @@ -1040,11 +1039,14 @@ export class Realm { /** * Add a listener {@link callback} for the specified {@link eventName}. - * @param eventName The name of event that should cause the callback to be called. - * @param callback Function to be called when a change event occurs. - * Each callback will only be called once per event, regardless of the number of times - * it was added. - * @throws an {@link Error} If an invalid event {@link eventName} is supplied, if Realm is closed or if {@link callback} is not a function. + * @param eventName - The name of event that should cause the callback to be called. + * @param callback - Function to be called when a change event occurs. + * Each callback will only be called once per event, regardless of the number of times + * it was added. + * @param callback.realm - The Realm in which the change event occurred. + * @param callback.name - The name of the event that occurred. + * @param callback.schema - The schema of the Realm file when the event occurred. + * @throws An {@link Error} if an invalid event {@link eventName} is supplied, if Realm is closed or if {@link callback} is not a function. */ addListener(eventName: RealmEventName, callback: RealmListenerCallback): void { assert.open(this); @@ -1062,8 +1064,8 @@ export class Realm { /** * Remove the listener {@link callback} for the specified event {@link eventName}. - * @param eventName The event name. - * @param callback Function that was previously added as a listener for this event through the {@link addListener} method. + * @param eventName - The event name. + * @param callback - Function that was previously added as a listener for this event through the {@link addListener} method. * @throws an {@link Error} If an invalid event {@link eventName} is supplied, if Realm is closed or if {@link callback} is not a function. */ removeListener(eventName: RealmEventName, callback: RealmListenerCallback): void { @@ -1083,8 +1085,8 @@ export class Realm { /** * Remove all event listeners (restricted to the event {@link eventName}, if provided). - * @param eventName The name of the event whose listeners should be removed. - * @throws an {@link Error} When invalid event {@link eventName} is supplied + * @param eventName - The name of the event whose listeners should be removed. + * @throws An {@link Error} when invalid event {@link eventName} is supplied. */ removeAllListeners(eventName?: RealmEventName): void { assert.open(this); @@ -1115,6 +1117,7 @@ export class Realm { * be called instead of {@link commitTransaction} and the exception will be re-thrown to the caller of {@link write}. * * Nested transactions (calling {@link write} within {@link write}) is not possible. + * @param callback - Function to be called inside a write transaction. * @returns Returned value from the callback. */ write(callback: () => T): T { @@ -1136,7 +1139,7 @@ export class Realm { * When doing a transaction, it is highly recommended to do error handling. * If you don't handle errors, your data might become inconsistent. Error handling * will often involve canceling the transaction. - * @throws an {@link Error} If already in write transaction + * @throws An {@link Error} if already in write transaction * @see {@link cancelTransaction} * @see {@link commitTransaction} * @example @@ -1200,9 +1203,9 @@ export class Realm { * * Note that if this method is called from within a write transaction, the current data is written, * not the data from the point when the previous write transaction was committed. - * @param config Realm configuration that describes the output realm. + * @param config - Realm configuration that describes the output realm. */ - writeCopyTo(config: Configuration) { + writeCopyTo(config: Configuration): void { assert.outTransaction(this, "Can only convert Realms outside a transaction."); validateConfiguration(config); const { bindingConfig } = Realm.transformConfig(config); @@ -1235,9 +1238,7 @@ export class Realm { // callback and not here. } - /** - * @internal - */ + /** @internal */ public getClassHelpers( arg: string | binding.TableKey | RealmObject | Constructor>, ): ClassHelpers { @@ -1259,7 +1260,7 @@ export class Realm { } /** - * @param objectSchema The schema of the object. + * @param objectSchema - The schema of the object. * @returns `true` if the object is marked for asymmetric sync, otherwise `false`. */ function isAsymmetric(objectSchema: binding.ObjectSchema): boolean { @@ -1267,7 +1268,7 @@ function isAsymmetric(objectSchema: binding.ObjectSchema): boolean { } /** - * @param objectSchema The schema of the object. + * @param objectSchema - The schema of the object. * @returns `true` if the object is marked as embedded, otherwise `false`. */ function isEmbedded(objectSchema: binding.ObjectSchema): boolean { diff --git a/packages/realm/src/Results.ts b/packages/realm/src/Results.ts index 2b9c97f34d..962f3a776e 100644 --- a/packages/realm/src/Results.ts +++ b/packages/realm/src/Results.ts @@ -36,6 +36,7 @@ import { * snapshot()}, however, will **not** live update * (and listener callbacks added through addListener() * will thus never be called). + * @see https://www.mongodb.com/docs/realm/sdk/react-native/model-data/data-types/collections/ */ export class Results extends OrderedCollection { /** @@ -82,16 +83,19 @@ export class Results extends OrderedCollection { throw new Error("Cannot assign to read only property 'length'"); } + /* + * @returns A string representation of the query and sorting bound to the results. + */ description(): string { return binding.Helpers.getResultsDescription(this.internal); } /** * Bulk update objects in the collection. - * @param propertyName The name of the property. - * @param value The updated property value. - * @throws an {@link Error} If no property with the name exists. - * @since 2.0.0-rc20 + * @param propertyName - The name of the property. + * @param value - The updated property value. + * @throws An {@link Error} if no property with the name exists. + * @since 2.0.0 */ update(propertyName: keyof Unmanaged, value: Unmanaged[typeof propertyName]): void { const { @@ -114,7 +118,7 @@ export class Results extends OrderedCollection { /** * Add this query result to the set of active subscriptions. The query will be joined * via an `OR` operator with any existing queries for the same type. - * @param options Options to use when adding this subscription (e.g. a name or wait behavior). + * @param options - Options to use when adding this subscription (e.g. a name or wait behavior). * @returns A promise that resolves to this {@link Results} instance. * @experimental This API is experimental and may change or be removed. */ @@ -156,10 +160,18 @@ export class Results extends OrderedCollection { }); } + /** + * Checks if this results collection has not been deleted and is part of a valid Realm. + * @returns `true` if the collection can be safely accessed. + */ isValid(): boolean { return this.internal.isValid; } + /** + * Checks if this collection result is empty. + * @returns `true` if the collection result is empty, `false` if not. + */ isEmpty(): boolean { return this.internal.size() === 0; } diff --git a/packages/realm/src/Set.ts b/packages/realm/src/Set.ts index 91c4772c3d..468547d629 100644 --- a/packages/realm/src/Set.ts +++ b/packages/realm/src/Set.ts @@ -37,6 +37,7 @@ import { * If values in a Set are required to have some order, it must be implemented * by the developer by, for example, wrapping values in an object that holds * a user-supplied insertion order. + * @see https://www.mongodb.com/docs/realm/sdk/react-native/model-data/data-types/sets/ */ export class RealmSet extends OrderedCollection { /** @internal */ @@ -56,24 +57,24 @@ export class RealmSet extends OrderedCollection { }); } /** - * Number of items in the set + * @returns The number of values in the Set. */ get size(): number { return this.length; } /** - * Checks if this set has not been deleted and is part of a valid Realm. + * Checks if this Set has not been deleted and is part of a valid Realm. * @returns `true` if the set can be safely accessed, `false` if not. */ - isValid() { + isValid(): boolean { return this.internal.isValid; } /** - * Delete a value from the Set - * @param value Value to delete from the Set - * @throws an {@link Error} If not inside a write transaction. + * Delete a value from the Set. + * @param value - Value to delete from the Set. + * @throws An {@link Error} if not inside a write transaction. * @returns `true` if the value existed in the Set prior to deletion, `false` if not. */ delete(value: T): boolean { @@ -83,12 +84,12 @@ export class RealmSet extends OrderedCollection { } /** - * Add a new value to the Set - * @param value Value to add to the Set - * @throws {TypeError} If a `value` is not of a type which can be stored in - * the Set, or if an object being added to the Set does not match the for the Set. - * @throws an {@link Error} If not inside a write transaction. - * @returns The Set itself, after adding the new value + * Add a new value to the Set. + * @param value - Value to add to the Set. + * @throws A {@link TypeError} if a `value` is not of a type which can be stored in + * the Set, or if an object being added to the Set does not match the for the Set. + * @throws An {@link Error} if not inside a write transaction. + * @returns The Set itself, after adding the new value. */ add(value: T): this { assert.inTransaction(this.realm); @@ -97,8 +98,8 @@ export class RealmSet extends OrderedCollection { } /** - * Remove all values from the Set - * @throws an {@link Error} If not inside a write transaction. + * Remove all values from the Set. + * @throws An {@link Error} if not inside a write transaction. */ clear(): void { assert.inTransaction(this.realm); @@ -106,18 +107,23 @@ export class RealmSet extends OrderedCollection { } /** - * Check for existence of a value in the Set - * @param value Value to search for in the Set - * @throws {TypeError} If a `value` is not of a type which can be stored in - * the Set, or if an object being added to the Set does not match the - * **object schema** for the Set. + * Check for existence of a value in the Set. + * @param value - Value to search for in the Set + * @throws A {@link TypeError} if a `value` is not of a type which can be stored in + * the Set, or if an object being added to the Set does not match the + * **object schema** for the Set. * @returns `true` if the value exists in the Set, `false` if not. */ has(value: T): boolean { return this.includes(value); } - *entries() { + /** + * @see {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set/entries | Set.prototype.entries()} + * @returns An iterator over the entries of the Set. Each entry is a two-element array + * containing the value from the Set, followed by a copy of the same value (`[value, value]`). + */ + *entries(): Generator<[T, T]> { for (const value of this.values()) { yield [value, value] as [T, T]; } diff --git a/packages/realm/src/app-services/ApiKeyAuth.ts b/packages/realm/src/app-services/ApiKeyAuth.ts index cad2c23bf8..5b7ae8495d 100644 --- a/packages/realm/src/app-services/ApiKeyAuth.ts +++ b/packages/realm/src/app-services/ApiKeyAuth.ts @@ -92,7 +92,7 @@ export class ApiKeyAuth { /** * Deletes an API key associated with the current user. - * @param keyId the id of the API key to delete + * @param keyId the ID of the API key to delete */ async delete(keyId: string) { await this.internal.deleteApiKey(new BSON.ObjectId(keyId), this.user); @@ -100,7 +100,7 @@ export class ApiKeyAuth { /** * Enables an API key associated with the current user. - * @param keyId the id of the API key to enable + * @param keyId the ID of the API key to enable */ async enable(keyId: string) { await this.internal.enableApiKey(new BSON.ObjectId(keyId), this.user); @@ -108,7 +108,7 @@ export class ApiKeyAuth { /** * Disable an API key associated with the current user. - * @param keyId the id of the API key to disable + * @param keyId the ID of the API key to disable */ async disable(keyId: string) { await this.internal.disableApiKey(new BSON.ObjectId(keyId), this.user); diff --git a/packages/realm/src/app-services/App.ts b/packages/realm/src/app-services/App.ts index d72a344707..3ae02efe07 100644 --- a/packages/realm/src/app-services/App.ts +++ b/packages/realm/src/app-services/App.ts @@ -82,8 +82,8 @@ export type AppConfiguration = { */ export type LocalAppConfiguration = { /** - * The name / id of the local app. - * Note: This should be the name or a bundle id of your app, not the Atlas App Services application. + * The name / ID of the local app. + * Note: This should be the name or a bundle ID of your app, not the Atlas App Services application. */ name?: string; @@ -111,10 +111,10 @@ export class App>(); /** - * Get or create a singleton Realm App from an id. - * Calling this function multiple times with the same id will return the same instance. + * Get or create a singleton Realm App from an ID. + * Calling this function multiple times with the same ID will return the same instance. * @deprecated Use {@link App.get}. - * @param id The Realm App id visible from the Atlas App Services UI or a configuration. + * @param id - The Realm App ID visible from the Atlas App Services UI or a configuration. * @returns The Realm App instance. */ public static getApp(id: string): App { @@ -122,9 +122,9 @@ export class App> { const userInternal = await this.internal.logInWithCredentials(credentials.internal); return User.get(userInternal, this); } /** * Perform operations related to the email/password auth provider. + * @returns An instance of the email password authentication provider. */ public get emailPasswordAuth(): EmailPasswordAuth { // TODO: Add memoization @@ -250,6 +254,7 @@ export class App | null { const currentUser = this.internal.currentUser; @@ -257,7 +262,8 @@ export class App>> { return Object.fromEntries(this.internal.allUsers.map((user) => [user.identity, User.get(user, this)])); @@ -266,7 +272,7 @@ export class App { await this.internal.removeUser(user.internal); } @@ -285,22 +291,24 @@ export class App { await this.internal.deleteUser(user.internal); } /** * Adds a listener that will be fired on various user events. * This includes login, logout, switching users, linking users and refreshing custom data. + * @param callback - A callback function that will be called when the event occurs. */ - public addListener(callback: AppChangeCallback) { + public addListener(callback: AppChangeCallback): void { this.listeners.add(callback); } /** * Removes an event listener previously added via {@link App.addListener}. + * @param callback - The callback to remove. */ - public removeListener(callback: AppChangeCallback) { + public removeListener(callback: AppChangeCallback): void { this.listeners.remove(callback); } diff --git a/packages/realm/src/app-services/BaseSubscriptionSet.ts b/packages/realm/src/app-services/BaseSubscriptionSet.ts index d85760659f..3f5da5dd2a 100644 --- a/packages/realm/src/app-services/BaseSubscriptionSet.ts +++ b/packages/realm/src/app-services/BaseSubscriptionSet.ts @@ -132,8 +132,8 @@ const PROXY_HANDLER: ProxyHandler = { * Array API, e.g. `[...realm.subscriptions][0]`. */ export abstract class BaseSubscriptionSet { - /**@internal */ - protected constructor(/**@internal */ protected internal: binding.SyncSubscriptionSet) { + /** @internal */ + protected constructor(/** @internal */ protected internal: binding.SyncSubscriptionSet) { Object.defineProperty(this, "internal", { enumerable: false, configurable: false, @@ -146,6 +146,7 @@ export abstract class BaseSubscriptionSet { /** * Whether there are no subscriptions in the set. + * @returns `true` if there are no subscriptions in the set, `false` otherwise. */ get isEmpty(): boolean { return this.internal.size === 0; @@ -154,13 +155,14 @@ export abstract class BaseSubscriptionSet { /** * The version of the SubscriptionSet. This is incremented every time a * {@link SubscriptionSet.update} is applied. + * @returns The version of the {@link SubscriptionSet}. */ get version(): number { return Number(this.internal.version); } /** - * The state of the SubscriptionSet. + * @returns The state of the SubscriptionSet. */ get state(): SubscriptionSetState { const state = this.internal.state; @@ -182,15 +184,16 @@ export abstract class BaseSubscriptionSet { } /** - * If `state` is {@link SubscriptionSetState.Error}, this will be a `string` representing - * why the SubscriptionSet is in an error state. It will be `null` if there is no error. + * If `state` is {@link SubscriptionSetState.Error}, this will be a string representing + * why the {@link SubscriptionSet} is in an error state. It will be `null` if there is no error. + * @returns A string representing the error, or `null` if there is no error. */ get error(): string | null { return this.state === SubscriptionSetState.Error ? this.internal.errorStr : null; } /** - * The number of subscriptions in the set. + * @returns The number of subscriptions in the set. */ get length(): number { return this.internal.size; @@ -198,7 +201,7 @@ export abstract class BaseSubscriptionSet { /** * Find a subscription by name. - * @param name The name to search for. + * @param name - The name to search for. * @returns The named subscription, or `null` if the subscription is not found. */ findByName(name: string): Subscription | null { @@ -210,7 +213,7 @@ export abstract class BaseSubscriptionSet { /** * Find a subscription by query. Will match both named and unnamed subscriptions. - * @param query The query to search for, represented as a {@link Results} instance, + * @param query - The query to search for, represented as a {@link Results} instance, * e.g. `Realm.objects("Cat").filtered("age > 10")`. * @returns The subscription with the specified query, or `null` if the subscription is not found. */ diff --git a/packages/realm/src/app-services/Credentials.ts b/packages/realm/src/app-services/Credentials.ts index b6334648ff..221b8271bb 100644 --- a/packages/realm/src/app-services/Credentials.ts +++ b/packages/realm/src/app-services/Credentials.ts @@ -49,8 +49,8 @@ export class Credentials { * Creates credentials for an anonymous user. These can only be used once - using them a second * time will result in a different user being logged in. If you need to get a user that has already logged * in with the Anonymous credentials, use {@link App.currentUser} or {@link App.allUsers}. - * @param reuse Reuse any existing anonymous user already logged in. - * @return An instance of `Credentials` that can be used in {@link App.logIn}. + * @param reuse - Reuse any existing anonymous user already logged in. + * @returns An instance of `Credentials` that can be used in {@link App.logIn}. * @see https://docs.mongodb.com/realm/authentication/anonymous/ */ static anonymous(reuse = true): Credentials { @@ -59,7 +59,7 @@ export class Credentials { /** * Creates credentials based on a login with an email address and a password. - * @return {Credentials} An instance of `Credentials` that can be used in {@link App.logIn}. + * @returns An instance of `Credentials` that can be used in {@link App.logIn}. * @see https://www.mongodb.com/docs/atlas/app-services/authentication/email-password/ */ static emailPassword(credentials: { email: string; password: string }): Credentials; @@ -77,8 +77,8 @@ export class Credentials { /** * Creates credentials from an API key. - * @param key A string identifying the API key. - * @return An instance of `Credentials` that can be used in {@link App.logIn}. + * @param key - A string identifying the API key. + * @returns An instance of `Credentials` that can be used in {@link App.logIn}. * @see https://www.mongodb.com/docs/atlas/app-services/authentication/api-key/ */ static apiKey(key: string): Credentials { @@ -87,8 +87,8 @@ export class Credentials { /** * Creates credentials based on an Apple login. - * @param token An Apple authentication token, obtained by logging into Apple. - * @return An instance of `Credentials` that can be used in {@link App.logIn}. + * @param token - An Apple authentication token, obtained by logging into Apple. + * @returns An instance of `Credentials` that can be used in {@link App.logIn}. * @see https://www.mongodb.com/docs/atlas/app-services/authentication/apple/ */ static apple(token: string): Credentials { @@ -97,8 +97,8 @@ export class Credentials { /** * Creates credentials based on a Facebook login. - * @param token A Facebook authentication token, obtained by logging into Facebook. - * @return An instance of `Credentials` that can be used in {@link App.logIn}. + * @param token - A Facebook authentication token, obtained by logging into Facebook. + * @returns An instance of `Credentials` that can be used in {@link App.logIn}. * @see https://www.mongodb.com/docs/atlas/app-services/authentication/facebook/ */ static facebook(token: string): Credentials { @@ -107,8 +107,8 @@ export class Credentials { /** * Creates credentials based on a Google login. - * @param authObject An object with either an `authCode` or `idToken` property. - * @return {Credentials} An instance of `Credentials` that can be used in {@link App.logIn}. + * @param authObject - An object with either an `authCode` or `idToken` property. + * @returns An instance of `Credentials` that can be used in {@link App.logIn}. * @see https://www.mongodb.com/docs/atlas/app-services/authentication/google/ */ static google(authObject: { authCode: string } | { idToken: string }): Credentials; @@ -126,8 +126,8 @@ export class Credentials { /** * Creates credentials with a JSON Web Token (JWT) provider and user identifier. - * @param token A string identifying the user. Usually an identity token or a username. - * @return An instance of `Credentials` that can be used in {@link App.logIn}. + * @param token - A string identifying the user. Usually an identity token or a username. + * @returns An instance of `Credentials` that can be used in {@link App.logIn}. * @see https://www.mongodb.com/docs/atlas/app-services/authentication/custom-jwt/ */ static jwt(token: string): Credentials { @@ -136,8 +136,8 @@ export class Credentials { /** * Creates credentials with an Atlas App Services function and user identifier. - * @param payload An object identifying the user. Usually an identity token or a username. - * @return An instance of `Credentials` that can be used in {@link App.logIn}. + * @param payload - An object identifying the user. Usually an identity token or a username. + * @returns An instance of `Credentials` that can be used in {@link App.logIn}. * @see https://www.mongodb.com/docs/atlas/app-services/authentication/custom-function/ */ static function(payload: object): Credentials { diff --git a/packages/realm/src/app-services/EmailPasswordAuth.ts b/packages/realm/src/app-services/EmailPasswordAuth.ts index 808f73cb27..4076d743d5 100644 --- a/packages/realm/src/app-services/EmailPasswordAuth.ts +++ b/packages/realm/src/app-services/EmailPasswordAuth.ts @@ -34,7 +34,7 @@ export class EmailPasswordAuth { /** * Registers a new email identity with the email/password provider, * and sends a confirmation email to the provided address. - * @param details The new user's email and password details + * @param details - The new user's email and password details. * @param details.email - The email address of the user to register. * @param details.password - The password that the user created for the new username/password identity. * @since v10.10.0 @@ -45,7 +45,7 @@ export class EmailPasswordAuth { /** * Confirms an email identity with the email/password provider. - * @param details The received token and ID details + * @param details - The received token and ID details * @param details.token - The confirmation token that was emailed to the user. * @param details.tokenId - The confirmation token id that was emailed to the user. * @since v10.10.0 @@ -57,7 +57,7 @@ export class EmailPasswordAuth { /** * Re-sends a confirmation email to a user that has registered but * not yet confirmed their email address. - * @param details The associated email details + * @param details - The associated email details. * @param details.email - The email address of the user to re-send a confirmation for. * @since v10.10.0 */ @@ -68,7 +68,7 @@ export class EmailPasswordAuth { /** * Re-run the custom confirmation function for user that has registered but * not yet confirmed their email address. - * @param details The associated email details + * @param details - The associated email details. * @param details.email - The email address of the user to re-run the confirmation for. * @since v10.10.0 */ @@ -78,7 +78,7 @@ export class EmailPasswordAuth { /** * Resets the password of an email identity using the password reset token emailed to a user. - * @param details The token and password details for the reset + * @param details - The token and password details for the reset. * @param details.password - The desired new password. * @param details.token - The password reset token that was emailed to the user. * @param details.tokenId - The password reset token id that was emailed to the user. @@ -90,7 +90,7 @@ export class EmailPasswordAuth { /** * Sends an email to the user for resetting the password. - * @param details The email details to send the reset to + * @param details - The email details to send the reset to. * @param details.email - The email address of the user to re-send a confirmation for. * @since v10.10.0 */ @@ -100,7 +100,7 @@ export class EmailPasswordAuth { /** * Call the custom function to reset the password. - * @param details The new user's email and password details + * @param details - The new user's email and password details. * @param details.email - The email address of the user to register. * @param details.password - The password that the user created for the new username/password identity. * @param args One or more arguments to pass to the function. diff --git a/packages/realm/src/app-services/MongoDBCollection.ts b/packages/realm/src/app-services/MongoDBCollection.ts index bc73c9c85c..1aa02665f0 100644 --- a/packages/realm/src/app-services/MongoDBCollection.ts +++ b/packages/realm/src/app-services/MongoDBCollection.ts @@ -122,7 +122,7 @@ export type UpdateOptions = { */ export type Document = { /** - * The id of the document. + * The ID of the document. */ _id: IdType; }; @@ -137,7 +137,7 @@ export type NewDocument = Omit & Partial = { /** - * The id of the inserted document + * The ID of the inserted document */ readonly insertedId: IdType; }; @@ -147,7 +147,7 @@ export type InsertOneResult = { */ export type InsertManyResult = { /** - * The ids of the inserted documents + * The IDs of the inserted documents */ readonly insertedIds: IdType[]; }; @@ -267,7 +267,7 @@ export type ChangeEventId = unknown; * shard key for the document. The _id field is not repeated if it is already a part of the shard key. */ export type DocumentKey = { - /** The id of the document. */ + /** The ID of the document. */ _id: IdType; } & Record; @@ -275,7 +275,7 @@ export type DocumentKey = { * A base change event containing the properties which apply across operation types. */ export type BaseChangeEvent = { - /** The id of the change event. */ + /** The ID of the change event. */ _id: ChangeEventId; /** The type of operation which was performed on the document. */ operationType: T; @@ -395,9 +395,9 @@ export type ChangeEvent = export class MongoDBCollection { private functions: DefaultFunctionsFactory; - /**@internal */ + /** @internal */ constructor( - /**@internal */ private user: User, + /** @internal */ private user: User, public readonly serviceName: string, public readonly databaseName: string, private readonly collectionName: string, @@ -414,9 +414,9 @@ export class MongoDBCollection { /** * Finds the documents which match the provided query. - * @param filter An optional filter applied to narrow down the results. - * @param options Additional options to apply. - * @returns The documents. + * @param filter - An optional filter applied to narrow down the results. + * @param options - Additional options to apply. + * @returns A promise that resolves to the found documents. */ find(filter: Filter = {}, options: FindOptions = {}): Promise { return this.functions.find({ @@ -431,9 +431,9 @@ export class MongoDBCollection { /** * Finds a document which matches the provided filter. - * @param filter A filter applied to narrow down the result. - * @param options Additional options to apply. - * @returns The document. + * @param filter - A filter applied to narrow down the result. + * @param options - Additional options to apply. + * @returns A promise that resolves to the found document. */ findOne(filter: Filter = {}, options: FindOneOptions = {}): Promise { return this.functions.findOne({ @@ -447,10 +447,10 @@ export class MongoDBCollection { /** * Finds a document which matches the provided query and performs the desired update to individual fields. - * @param filter A filter applied to narrow down the result. - * @param update The new values for the document. - * @param options Additional options to apply. - * @returns The document found before updating it. + * @param filter - A filter applied to narrow down the result. + * @param update - The new values for the document. + * @param options - Additional options to apply. + * @returns A promise that resolves to the found document before applying the update. */ findOneAndUpdate(filter: Filter, update: Update, options: FindOneAndModifyOptions = {}): Promise { return this.functions.findOneAndUpdate({ @@ -467,10 +467,10 @@ export class MongoDBCollection { /** * Finds a document which matches the provided filter and replaces it with a new document. - * @param filter A filter applied to narrow down the result. - * @param replacement The new replacing document. - * @param options Additional options to apply. - * @returns The document found before replacing it. + * @param filter - A filter applied to narrow down the result. + * @param replacement - The new replacing document. + * @param options - Additional options to apply. + * @returns A promise that resolves to the found document found before replacement. */ findOneAndReplace(filter: Filter, replacement: unknown, options: FindOneAndModifyOptions = {}): Promise { return this.functions.findOneAndReplace({ @@ -487,9 +487,9 @@ export class MongoDBCollection { /** * Finds a document which matches the provided filter and deletes it - * @param filter A filter applied to narrow down the result. - * @param options Additional options to apply. - * @returns The document found before deleting it. + * @param filter - A filter applied to narrow down the result. + * @param options - Additional options to apply. + * @returns A promise that resolves to the found document before deletion. */ findOneAndDelete(filter: Filter = {}, options: FindOneOptions = {}): Promise { return this.functions.findOneAndDelete({ @@ -503,8 +503,8 @@ export class MongoDBCollection { /** * Runs an aggregation framework pipeline against this collection. - * @param pipeline An array of aggregation pipeline stages. - * @returns The result. + * @param pipeline - An array of aggregation pipeline stages. + * @returns A promise that resolves to the aggregation result. */ aggregate(pipeline: AggregatePipelineStage[]): Promise { return this.functions.aggregate({ @@ -523,6 +523,9 @@ export class MongoDBCollection { * - On a sharded cluster, the resulting count will not correctly filter out * {@link https://www.mongodb.com/docs/manual/reference/glossary/#std-term-orphaned-document orphaned documents}. * - After an unclean shutdown or file copy based initial sync, the count may be incorrect. + * @param filter - An optional filter applied to narrow down the results. + * @param options - Additional options to apply. + * @returns A promise that resolves to the number of documents matching the filter. */ count(filter: Filter = {}, options: CountOptions = {}): Promise { return this.functions.count({ @@ -536,8 +539,8 @@ export class MongoDBCollection { /** * Inserts a single document into the collection. * Note: If the document is missing an _id, one will be generated for it by the server. - * @param document The document. - * @returns The result. + * @param document - The document to insert. + * @returns A promise that resolves an object containing the inserted object ID (`insertedId`). */ insertOne(document: NewDocument): Promise> { return this.functions.insertOne({ @@ -550,8 +553,8 @@ export class MongoDBCollection { /** * Inserts an array of documents into the collection. * If any values are missing identifiers, they will be generated by the server. - * @param documents The array of documents. - * @returns The result. + * @param documents - The array of documents to insert. + * @returns A promise that resolves to an object containing an array of IDs inserted (`insertedIds`). */ insertMany(documents: NewDocument[]): Promise> { return this.functions.insertMany({ @@ -563,8 +566,8 @@ export class MongoDBCollection { /** * Deletes a single matching document from the collection. - * @param filter A filter applied to narrow down the result. - * @returns The result. + * @param filter - A filter applied to narrow down the result. + * @returns A promise that resolves to an object containing the number of deleted documents (`deletedCount`). */ deleteOne(filter: Filter = {}): Promise { return this.functions.deleteOne({ @@ -576,9 +579,9 @@ export class MongoDBCollection { /** * Deletes multiple documents. - * @param filter A filter applied to narrow down the result. If omitted, it defaults + * @param filter - A filter applied to narrow down the result. If omitted, it defaults * to `{}` which deletes all documents in the collection. - * @returns The result. + * @returns A promise that resolves to an object containing the number of deleted documents (`deletedCount`). */ deleteMany(filter: Filter = {}): Promise { return this.functions.deleteMany({ @@ -590,10 +593,17 @@ export class MongoDBCollection { /** * Updates a single document matching the provided filter in this collection. - * @param filter A filter applied to narrow down the result. - * @param update The new values for the document. - * @param options Additional options to apply. - * @returns The result. + * @param filter - A filter applied to narrow down the result. + * @param update - The new values for the document. + * @param options - Additional options to apply. + * @returns A promise that resolves to an object containing: + * ``` + * { + * matchedCount: number; + * modifiedCount: number; + * upsertedId: IdType | undefined; + * } + * ``` */ updateOne(filter: Filter, update: Update, options: UpdateOptions = {}): Promise> { return this.functions.updateOne({ @@ -608,10 +618,17 @@ export class MongoDBCollection { /** * Updates multiple documents matching the provided filter in this collection. - * @param filter A filter applied to narrow down the result. - * @param update The new values for the documents. - * @param options Additional options to apply. - * @returns The result. + * @param filter - A filter applied to narrow down the result. + * @param update - The new values for the documents. + * @param options - Additional options to apply. + * @returns A promise that resolves to an object containing: + * ``` + * { + * matchedCount: number; + * modifiedCount: number; + * upsertedId: IdType | undefined; + * } + * ``` */ updateMany(filter: Filter, update: Update, options: UpdateOptions = {}): Promise> { return this.functions.updateMany({ @@ -634,8 +651,9 @@ export class MongoDBCollection { * * 1. Polyfills for `fetch` and `ReadableStream`: https://www.npmjs.com/package/react-native-polyfill-globals * 2. Babel plugin enabling async generator syntax: https://npmjs.com/package/@babel/plugin-proposal-async-generator-functions - * @param options.filter A filter for which change events you want to watch. - * @param options.ids A list of document ids for which change events you want to watch. + * @param options.filter - A filter for which change events you want to watch. + * @param options.ids - A list of document IDs for which change events you want to watch. + * @returns An async generator of change events. * @see https://docs.mongodb.com/manual/reference/change-events/ */ watch(): AsyncGenerator>; diff --git a/packages/realm/src/app-services/MutableSubscriptionSet.ts b/packages/realm/src/app-services/MutableSubscriptionSet.ts index 0e996bfbf2..cfa734f5b8 100644 --- a/packages/realm/src/app-services/MutableSubscriptionSet.ts +++ b/packages/realm/src/app-services/MutableSubscriptionSet.ts @@ -87,11 +87,11 @@ export class MutableSubscriptionSet extends BaseSubscriptionSet { // rather than `(this.internal as binding.MutableSyncSubscriptionSet).someOwnMember`. // (`this.internal = internal` cannot be used in the constructor due to the proxy // handler in BaseSubscriptionSet making it non-writable.) - /**@internal */ + /** @internal */ protected declare internal: binding.MutableSyncSubscriptionSet; - /**@internal */ - constructor(/**@internal */ internal: binding.MutableSyncSubscriptionSet) { + /** @internal */ + constructor(/** @internal */ internal: binding.MutableSyncSubscriptionSet) { super(internal); } @@ -101,9 +101,9 @@ export class MutableSubscriptionSet extends BaseSubscriptionSet { * * A query is represented by a {@link Results} instance returned from {@link Realm.objects}, * for example: `mutableSubs.add(realm.objects("Cat").filtered("age > 10"));`. - * @param query A {@link Results} instance representing the query to subscribe to. - * @param options An optional {@link SubscriptionOptions} object containing options to - * use when adding this subscription (e.g. to give the subscription a name). + * @param query - A {@link Results} instance representing the query to subscribe to. + * @param options - An optional {@link SubscriptionOptions} object containing options to + * use when adding this subscription (e.g. to give the subscription a name). * @returns A `Subscription` instance for the new subscription. */ add(query: AnyResults, options?: SubscriptionOptions): Subscription { @@ -142,7 +142,7 @@ export class MutableSubscriptionSet extends BaseSubscriptionSet { /** * Remove a subscription with the given query from the SubscriptionSet. - * @param query A {@link Results} instance representing the query to remove a subscription to. + * @param query - A {@link Results} instance representing the query to remove a subscription to. * @returns `true` if the subscription was removed, `false` if it was not found. */ remove(query: AnyResults): boolean { @@ -153,7 +153,7 @@ export class MutableSubscriptionSet extends BaseSubscriptionSet { /** * Remove a subscription with the given name from the SubscriptionSet. - * @param name The name of the subscription to remove. + * @param name - The name of the subscription to remove. * @returns `true` if the subscription was removed, `false` if it was not found. */ removeByName(name: string): boolean { @@ -164,7 +164,7 @@ export class MutableSubscriptionSet extends BaseSubscriptionSet { /** * Remove the specified subscription from the SubscriptionSet. - * @param subscription The {@link Subscription} instance to remove. + * @param subscription - The {@link Subscription} instance to remove. * @returns `true` if the subscription was removed, `false` if it was not found. */ removeSubscription(subscription: Subscription): boolean { @@ -175,7 +175,7 @@ export class MutableSubscriptionSet extends BaseSubscriptionSet { /** * Remove all subscriptions for the specified object type from the SubscriptionSet. - * @param objectType The string name of the object type to remove all subscriptions for. + * @param objectType - The string name of the object type to remove all subscriptions for. * @returns The number of subscriptions removed. */ removeByObjectType(objectType: string): number { diff --git a/packages/realm/src/app-services/PushClient.ts b/packages/realm/src/app-services/PushClient.ts index 18b269ec65..09027680a9 100644 --- a/packages/realm/src/app-services/PushClient.ts +++ b/packages/realm/src/app-services/PushClient.ts @@ -34,16 +34,18 @@ export class PushClient { /** * Register this device with the user. - * @param token A Firebase Cloud Messaging (FCM) token, retrieved via the firebase SDK. + * @param token - A Firebase Cloud Messaging (FCM) token, retrieved via the firebase SDK. + * @returns A promise that resolves once the device has been registered. */ - async register(token: string) { + async register(token: string): Promise { await this.internal.registerDevice(token, this.user); } /** * Deregister this device with the user, to disable sending messages to this device. + * @returns A promise that resolves once the device has been deregistered. */ - async deregister() { + async deregister(): Promise { await this.internal.deregisterDevice(this.user); } } diff --git a/packages/realm/src/app-services/Subscription.ts b/packages/realm/src/app-services/Subscription.ts index 101f2934f0..a2686c9d58 100644 --- a/packages/realm/src/app-services/Subscription.ts +++ b/packages/realm/src/app-services/Subscription.ts @@ -25,13 +25,14 @@ import { BSON, SubscriptionSet, binding } from "../internal"; * in a {@link SubscriptionSet.update} callback. */ export class Subscription { - /**@internal */ - constructor(/**@internal */ public internal: binding.SyncSubscription) { + /** @internal */ + constructor(/** @internal */ public internal: binding.SyncSubscription) { this.internal = internal; } /** * The ObjectId of the subscription. + * @returns The ObjectId of the subscription. */ get id(): BSON.ObjectId { return this.internal.id; @@ -39,6 +40,7 @@ export class Subscription { /** * The date when this subscription was created. + * @returns The date when this subscription was created. */ get createdAt(): Date { return this.internal.createdAt.toDate(); @@ -46,6 +48,7 @@ export class Subscription { /** * The date when this subscription was last updated. + * @returns The date when this subscription was last updated. */ get updatedAt(): Date { return this.internal.updatedAt.toDate(); @@ -54,6 +57,7 @@ export class Subscription { /** * The name given to this subscription when it was created. * If no name was set, this will be `null`. + * @returns The name of the subscription or `null` if unnamed. */ get name(): string | null { const result = this.internal.name; @@ -62,6 +66,7 @@ export class Subscription { /** * The type of objects the subscription refers to. + * @returns The type of objects the subscription refers to. */ get objectType(): string { return this.internal.objectClassName; @@ -70,6 +75,7 @@ export class Subscription { /** * The string representation of the query the subscription was created with. * If no filter or sort was specified, this will be `"TRUEPREDICATE"`. + * @returns The string representation of the query the subscription was created with. */ get queryString(): string { return this.internal.queryString; diff --git a/packages/realm/src/app-services/SubscriptionSet.ts b/packages/realm/src/app-services/SubscriptionSet.ts index 1fa8ad8fcb..cdd34fcf3e 100644 --- a/packages/realm/src/app-services/SubscriptionSet.ts +++ b/packages/realm/src/app-services/SubscriptionSet.ts @@ -36,8 +36,8 @@ import { * by calling methods on the corresponding {@link MutableSubscriptionSet} instance. */ export class SubscriptionSet extends BaseSubscriptionSet { - /**@internal */ - constructor(/**@internal */ private realm: Realm, internal: binding.SyncSubscriptionSet) { + /** @internal */ + constructor(/** @internal */ private realm: Realm, internal: binding.SyncSubscriptionSet) { super(internal); Object.defineProperty(this, "realm", { @@ -100,7 +100,7 @@ export class SubscriptionSet extends BaseSubscriptionSet { await this.waitForSynchronization(); } - /**@internal */ + /** @internal */ updateNoWait(callback: (mutableSubscriptions: MutableSubscriptionSet, realm: Realm) => void): void { assert.function(callback, "callback"); diff --git a/packages/realm/src/app-services/Sync.ts b/packages/realm/src/app-services/Sync.ts index cf65619839..c674cebd93 100644 --- a/packages/realm/src/app-services/Sync.ts +++ b/packages/realm/src/app-services/Sync.ts @@ -162,7 +162,8 @@ export class Sync { * Returns `true` if Realm still has a reference to any sync sessions regardless of their state. * If `false` is returned it means that no sessions currently exist. * @param [app] - The app where the Realm was opened. - @internal */ + * @internal + */ static _hasExistingSessions(app: App) { return app.internal.syncManager.hasExistingSessions; } diff --git a/packages/realm/src/app-services/SyncConfiguration.ts b/packages/realm/src/app-services/SyncConfiguration.ts index ae75d210ba..f6bb950146 100644 --- a/packages/realm/src/app-services/SyncConfiguration.ts +++ b/packages/realm/src/app-services/SyncConfiguration.ts @@ -184,7 +184,7 @@ export type SSLVerifyObject = { */ pemCertificate: string; /** - * The result of OpenSSL's preverification of the certificate. If `true`, + * The result of OpenSSL's pre-verification of the certificate. If `true`, * the certificate has been accepted and will generally be safe to trust. * If `false`, it has been rejected and the user should do an independent * validation step. diff --git a/packages/realm/src/app-services/SyncSession.ts b/packages/realm/src/app-services/SyncSession.ts index bcb3a8eddf..03c2c8740d 100644 --- a/packages/realm/src/app-services/SyncSession.ts +++ b/packages/realm/src/app-services/SyncSession.ts @@ -55,8 +55,8 @@ export enum ProgressMode { export type ProgressNotificationCallback = /** - * @param transferred The current number of bytes already transferred - * @param transferable The total number of transferable bytes (i.e. the number of bytes already transferred plus the number of bytes pending transfer) + * @param transferred - The current number of bytes already transferred + * @param transferable - The total number of transferable bytes (i.e. the number of bytes already transferred plus the number of bytes pending transfer) */ (transferred: number, transferable: number) => void; @@ -403,12 +403,12 @@ export class SyncSession { /** * Register a progress notification callback on a session object - * @param direction The progress direction to register for. - * @param mode The progress notification mode to use for the registration. + * @param direction - The progress direction to register for. + * @param mode - The progress notification mode to use for the registration. * Can be either: * - `reportIndefinitely` - the registration will stay active until the callback is unregistered * - `forCurrentlyOutstandingWork` - the registration will be active until only the currently transferable bytes are synced - * @param callback Called with the following arguments: + * @param callback - Called with the following arguments: * 1. `transferred`: The current number of bytes already transferred * 2. `transferable`: The total number of transferable bytes (the number of bytes already transferred plus the number of bytes pending transfer) */ @@ -418,15 +418,15 @@ export class SyncSession { /** * Unregister a progress notification callback that was previously registered with {@link addProgressNotification}. * Calling the function multiple times with the same callback is ignored. - * @param callback A previously registered progress callback + * @param callback - A previously registered progress callback. */ - removeProgressNotification(callback: ProgressNotificationCallback) { + removeProgressNotification(callback: ProgressNotificationCallback): void { PROGRESS_LISTENERS.remove(callback); } /** * Registers a connection notification on the session object. This will be notified about changes to the * underlying connection to the Realm Object Server. - * @param callback Called with the following arguments: + * @param callback - Called with the following arguments: * 1. `newState`: The new state of the connection * 2. `oldState`: The state the connection transitioned from. */ @@ -437,9 +437,9 @@ export class SyncSession { /** * Unregister a state notification callback that was previously registered with addStateNotification. * Calling the function multiple times with the same callback is ignored. - * @param callback A previously registered state callback. + * @param callback - A previously registered state callback. */ - removeConnectionNotification(callback: ConnectionNotificationCallback) { + removeConnectionNotification(callback: ConnectionNotificationCallback): void { CONNECTION_LISTENERS.remove(callback); } @@ -449,7 +449,7 @@ export class SyncSession { * times out, the download will still continue in the background. * * This method cannot be called before the Realm has been opened. - * @param timeoutMs maximum amount of time to wait in milliseconds before the promise will be rejected. If no timeout + * @param timeoutMs - maximum amount of time to wait in milliseconds before the promise will be rejected. If no timeout * is specified the method will wait forever. */ downloadAllServerChanges(timeoutMs?: number): Promise { @@ -468,7 +468,7 @@ export class SyncSession { * will still continue in the background. * * This method cannot be called before the Realm has been opened. - * @param timeoutMs Maximum amount of time to wait in milliseconds before the promise is rejected. If no timeout is specified the method will wait forever. + * @param timeoutMs - Maximum amount of time to wait in milliseconds before the promise is rejected. If no timeout is specified the method will wait forever. */ uploadAllLocalChanges(timeoutMs?: number): Promise { return this.withInternal( diff --git a/packages/realm/src/app-services/User.ts b/packages/realm/src/app-services/User.ts index eaa5412561..33ba049125 100644 --- a/packages/realm/src/app-services/User.ts +++ b/packages/realm/src/app-services/User.ts @@ -62,7 +62,7 @@ export enum UserState { */ export interface UserIdentity { /** - * The id of the identity. + * The ID of the identity. */ id: string; @@ -126,6 +126,7 @@ export class User< /** * The automatically-generated internal ID of the user. + * @returns The user ID as a string. */ get id(): string { return this.internal.identity; @@ -133,6 +134,7 @@ export class User< /** * The provider type used when authenticating the user. + * @returns The provider type as an enumerated string. */ get providerType(): ProviderType { const type = this.internal.providerType; @@ -144,7 +146,8 @@ export class User< } /** - * The id of the device. + * The ID of the device. + * @returns The device ID as a string or `null`. */ get deviceId(): string | null { return this.internal.deviceId; @@ -152,6 +155,7 @@ export class User< /** * The state of the user. + * @returns The state as an enumerated string. */ get state(): UserState { const state = this.internal.state; @@ -169,6 +173,7 @@ export class User< /** * The logged in state of the user. + * @returns `true` if the user is logged in, `false` otherwise. */ get isLoggedIn(): boolean { return this.internal.isLoggedIn; @@ -176,6 +181,7 @@ export class User< /** * The identities of the user at any of the app's authentication providers. + * @returns An array of {@link UserIdentity} objects. */ get identities(): UserIdentity[] { return this.internal.identities.map((identity) => { @@ -186,6 +192,7 @@ export class User< /** * The access token used when requesting a new access token. + * @returns The access token as a string or `null`. */ get accessToken(): string | null { return this.internal.accessToken; @@ -193,6 +200,7 @@ export class User< /** * The refresh token used when requesting a new access token. + * @returns The refresh token as a string or `null`. */ get refreshToken(): string | null { return this.internal.refreshToken; @@ -204,6 +212,7 @@ export class User< * For example, you might store a user’s preferred language, date of birth, or their local timezone. * * If this value has not been configured, it will be empty. + * @returns The custom data as an object. */ get customData(): CustomDataType { const result = this.internal.customData; @@ -215,6 +224,7 @@ export class User< /** * A profile containing additional information about the user. + * @returns The user profile data as an object. */ get profile(): UserProfileDataType { if (!this.cachedProfile) { @@ -225,6 +235,7 @@ export class User< /** * Use this to call functions defined by the Atlas App Services application, as this user. + * @returns A {@link FunctionsFactory} that can be used to call the app's functions. */ get functions(): FunctionsFactoryType { return createFactory(this as User, undefined); @@ -232,6 +243,7 @@ export class User< /** * Perform operations related to the API-key auth provider. + * @returns An {@link ApiKeyAuth} object that can be used to manage API keys. */ get apiKeys(): ApiKeyAuth { // TODO: Add memoization @@ -249,17 +261,18 @@ export class User< /** * Link the user with an identity represented by another set of credentials. - * @param credentials The credentials to use when linking. + * @param credentials - The credentials to use when linking. + * @returns A promise that resolves once the user has been linked with the credentials. */ - async linkCredentials(credentials: Credentials) { + async linkCredentials(credentials: Credentials): Promise { await this.app.internal.linkUser(this.internal, credentials.internal); } /** * Call a remote Atlas App Services Function by its name. - * Note: Consider using `functions[name]()` instead of calling this method. - * @param name Name of the App Services Function. - * @param args Arguments passed to the Function. + * @note Consider using `functions[name]()` instead of calling this method. + * @param name - Name of the App Services Function. + * @param args - Arguments passed to the Function. * @returns A promise that resolves to the value returned by the Function. * @example * // These are all equivalent: @@ -304,7 +317,7 @@ export class User< /** * Refresh the access token and derive custom data from it. - * @returns The newly fetched custom data. + * @returns A promise that resolves to the refreshed custom data. */ async refreshCustomData(): Promise { await this.app.internal.refreshCustomData(this.internal); @@ -314,7 +327,7 @@ export class User< /** * Use the Push service to enable sending push messages to this user via Firebase Cloud Messaging (FCM). * @deprecated https://www.mongodb.com/docs/atlas/app-services/reference/push-notifications/ - * @returns An service client with methods to register and deregister the device on the user. + * @returns A {@link PushClient} with methods to register and deregister the device on the user. */ push(serviceName: string): PushClient { const internal = this.app.internal.pushNotificationClient(serviceName); @@ -322,8 +335,8 @@ export class User< } /** - * @param serviceName The name of the MongoDB service to connect to. - * @returns A client enabling access to a MongoDB service. + * @param serviceName - The name of the MongoDB service to connect to. + * @returns A client enabling access to a {@link MongoDB} service. * @example * let blueWidgets = user.mongoClient("myService") * .db("myDb") @@ -354,6 +367,7 @@ export class User< /** * Adds a listener that will be fired on various user related events. * This includes auth token refresh, refresh token refresh, refresh custom user data, and logout. + * @param callback - The callback to be fired when the event occurs. */ addListener(callback: UserChangeCallback): void { this.listeners.add(callback); @@ -361,6 +375,7 @@ export class User< /** * Removes an event listener previously added via {@link User.addListener}. + * @param callback - The callback to be removed. */ removeListener(callback: UserChangeCallback): void { this.listeners.remove(callback);