UNPKG

realm

Version:

Realm by MongoDB is an offline-first mobile database: an alternative to SQLite and key-value stores

533 lines (532 loc) 28 kB
import { AnyList, AnyRealmObject, AnyResults, CanonicalObjectSchema, ClassHelpers, Configuration, Constructor, DefaultObject, LogLevel, LoggerCallback, ObjectSchema, ProgressRealmPromise, RealmListenerCallback, RealmObject, RealmObjectConstructor, Results, SubscriptionSet, SyncSession, Unmanaged, UpdateMode, binding } from "./internal"; type RealmSchemaExtra = Record<string, ObjectSchemaExtra | undefined>; type ObjectSchemaExtra = { constructor?: RealmObjectConstructor; defaults: Record<string, unknown>; }; export type RealmEventName = "change" | "schema" | "beforenotify"; /** @internal */ type InternalConfig = { internal?: binding.Realm; schemaExtras?: RealmSchemaExtra; realmExists?: boolean; }; /** * The Realm database. */ export declare class Realm { static defaultPath: string; private static internals; /** * Sets the log level. * @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 12.0.0 */ static setLogLevel(level: LogLevel): void; /** * 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. * @note The logger callback needs to be setup before opening the first realm. * @since 12.0.0 */ static setLogger(loggerCallback: LoggerCallback): void; /** * Clears the state by closing and deleting any Realm in the default directory and logout all users. * NOTE: Not a part of the public API and it's primarily used from the library's tests. * @private */ static clearTestState(): void; /** * Delete the Realm file for the given configuration. * @param config - The configuration for the Realm being deleted. * @throws An {@link Error} if anything in the provided {@link config} is invalid. */ static deleteFile(config: Configuration): void; /** * 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. * @returns `true` if the Realm exists on the device, `false` if not. */ static exists(arg?: Configuration | string): boolean; /** * Open a Realm asynchronously with a promise. If the Realm is synced, it will be fully * 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. * @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. */ static open(arg?: Configuration | string): ProgressRealmPromise; /** * 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 as an integer, or `-1` if no Realm exists at {@link path}. * @since 0.11.0 */ static schemaVersion(path: string, encryptionKey?: ArrayBuffer | ArrayBufferView): number; /** * Creates a template object for a Realm model class where all optional fields are undefined * 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. */ static createTemplateObject<T extends Record<string, unknown>>(objectSchema: ObjectSchema): T; /** * Copy any Realm files (i.e. `*.realm`) bundled with the application from the application * directory into the application's documents directory, so that they can be opened and used * by Realm. If the file already exists in the documents directory, it will not be * 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. * @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 * // not be overwritten, so it is safe to call this every time the app starts. * Realm.copyBundledRealmFiles(); * * const realm = await Realm.open({ * // This will open example.realm from the documents directory, with the bundled data in. * path: "example.realm" * }); * ``` * * This is only implemented for React Native. * @throws an {@link Error} If an I/O error occurred or method is not implemented. */ static copyBundledRealmFiles(): void; /** * TODO: Consider breaking this by ensuring a ".realm" suffix (coordinating with other SDK teams in the process) */ private static normalizePath; /** * @note When the path is relative and the config contains a sync object, Core will replace any existing file extension * or add the ".realm" suffix. */ private static determinePath; private static determineEncryptionKey; private static extractSchemaExtras; /** @internal */ static transformConfig(config: Configuration): { schemaExtras: RealmSchemaExtra; bindingConfig: binding.RealmConfig_Relaxed; }; private static determineSchemaMode; private static wrapMigration; /** * The Realms's representation in the binding. * @internal */ readonly internal: binding.Realm; /** * The sync session if this is a synced Realm */ readonly syncSession: SyncSession | null; private schemaExtras; private classes; private changeListeners; private beforeNotifyListeners; private schemaListeners; /** @internal */ currentUpdateMode: UpdateMode | undefined; /** * Create a new {@link Realm} instance, at the default path. * @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. */ constructor(path: string); /** * Create a new {@link Realm} instance using the provided {@link config}. If a Realm does not yet exist * at {@link Configuration.path | config.path} (or {@link Realm.defaultPath} if not provided), then this constructor * will create it with the provided {@link Configuration.schema | config.schema} (which is _required_ in this case). * Otherwise, the instance will access the existing Realm from the file at that path. * In this case, {@link Configuration.schema | config.schema} is _optional_ or not have changed, unless * {@link Configuration.schemaVersion | config.schemaVersion} is incremented, in which case the Realm will be automatically * 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. */ constructor(config: Configuration); /** @internal */ constructor(config: Configuration | null, internalConfig: InternalConfig); /** * Indicates if this Realm contains any objects. * @returns `true` if empty, `false` otherwise. * @readonly * @since 1.10.0 */ get isEmpty(): boolean; /** * 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 */ get path(): string; /** * Indicates if this Realm was opened as read-only. * @returns `true` if this Realm is read-only, `false` otherwise. * @readonly * @since 0.12.0 */ get isReadOnly(): boolean; /** * Indicates if this Realm was opened in-memory. * @returns `true` if this Realm is in-memory, `false` otherwise. * @readonly */ get isInMemory(): boolean; /** * 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 */ get schema(): CanonicalObjectSchema[]; /** * The current schema version of the Realm. * @returns The schema version of this Realm, as a `number`. * @readonly * @since 0.12.0 */ get schemaVersion(): number; /** * Indicates if this Realm is in a write transaction. * @returns `true` if in a write transaction, `false` otherwise. * @readonly * @since 1.10.3 */ get isInTransaction(): boolean; /** * Indicates if this Realm is in migration. * @returns `true` if in migration, `false` otherwise * @readonly * @since 12.3.0 */ get isInMigration(): boolean; /** * Indicates if this Realm has been closed. * @returns `true` if closed, `false` otherwise. * @readonly * @since 2.1.0 */ get isClosed(): boolean; /** * The latest set of flexible sync subscriptions. * @returns A {@link SubscriptionSet} object. * @throws An {@link Error} if flexible sync is not enabled for this app. */ get subscriptions(): SubscriptionSet; /** * Closes this Realm so it may be re-opened with a newer schema version. * All objects and collections from this Realm are no longer valid after calling this method. * The method is idempotent. */ close(): void; /** * 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. The default is `UpdateMode.Never`. * @returns A {@link RealmObject} or `undefined` if the object is asymmetric. */ create<T = DefaultObject>(type: string, values: Partial<T> | Partial<Unmanaged<T>>, mode?: UpdateMode.Never | UpdateMode.All | UpdateMode.Modified | boolean): RealmObject<T> & T; create<T extends AnyRealmObject>(type: Constructor<T>, values: Partial<T> | Partial<Unmanaged<T>>, mode?: UpdateMode.Never | UpdateMode.All | UpdateMode.Modified | boolean): T; /** * 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[] | AnyList | AnyResults | any): void; /** * 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. */ deleteModel(name: string): void; /** * **WARNING:** This will delete **all** objects in the Realm! */ deleteAll(): void; /** * 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. * @returns A {@link RealmObject} or `null` if no object is found. * @since 0.14.0 */ objectForPrimaryKey<T = DefaultObject>(type: string, primaryKey: T[keyof T]): (RealmObject<T> & T) | null; objectForPrimaryKey<T extends AnyRealmObject>(type: Constructor<T>, primaryKey: T[keyof T]): T | null; /** * 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. * @returns A {@link RealmObject} or `undefined` if the object key is not found. * @internal */ _objectForObjectKey<T = DefaultObject>(type: string, objectKey: string): (RealmObject<T> & T) | undefined; _objectForObjectKey<T extends RealmObject>(type: Constructor<T>, objectKey: string): T | undefined; /** * 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. * @returns Results that will live-update as objects are created, modified, and destroyed. */ objects<T = DefaultObject>(type: string): Results<RealmObject<T> & T>; objects<T extends AnyRealmObject = RealmObject & DefaultObject>(type: Constructor<T>): Results<T>; /** * 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. * @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; /** * 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. * @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; /** * 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. */ removeAllListeners(eventName?: RealmEventName): void; /** * Synchronously call the provided {@link callback} inside a write transaction. If an exception happens inside a transaction, * you’ll lose the changes in that transaction, but the Realm itself won’t be affected (or corrupted). * More precisely, {@link beginTransaction} and {@link commitTransaction} will be called * automatically. If any exception is thrown during the transaction {@link cancelTransaction} will * 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<T>(callback: () => T): T; /** * Initiate a write transaction. * * 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 * @see {@link cancelTransaction} * @see {@link commitTransaction} * @example * realm.beginTransaction(); * try { * realm.create('Person', { name: 'Arthur Dent', origin: 'Earth' }); * realm.create('Person', { name: 'Ford Prefect', origin: 'Betelgeuse Five' }); * realm.commitTransaction(); * } catch (e) { * realm.cancelTransaction(); * throw e; * } */ beginTransaction(): void; /** * Commit a write transaction. * @see {@link beginTransaction} */ commitTransaction(): void; /** * Cancel a write transaction. * @see {@link beginTransaction} */ cancelTransaction(): void; /** * Replaces all string columns in this Realm with a string enumeration column and compacts the * database file. * * Cannot be called from a write transaction. * * Compaction will not occur if other {@link Realm} instances exist. * * While compaction is in progress, attempts by other threads or processes to open the database will * wait. * * Be warned that resource requirements for compaction is proportional to the amount of live data in * the database. Compaction works by writing the database contents to a temporary database file and * then replacing the database with the temporary one. * @returns `true` if compaction succeeds, `false` if not. */ compact(): boolean; /** * Writes a compacted copy of the Realm with the given configuration. * * The destination file cannot already exist. * All conversions between synced and non-synced Realms are supported, and will be * performed according to the {@link config} parameter, which describes the desired output. * * 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. */ writeCopyTo(config: Configuration): void; /** * Update the schema of the Realm. * @param schema The schema which the Realm should be updated to use. * @internal */ _updateSchema(schema: ObjectSchema[]): void; /** @internal */ getClassHelpers<T>(arg: string | binding.TableKey | RealmObject<T> | Constructor<RealmObject<T>>): ClassHelpers; /** * Update subscriptions with the initial subscriptions if needed. * @param initialSubscriptions The initial subscriptions. * @param realmExists Whether the realm already exists. */ private handleInitialSubscriptions; } import * as internal from "./internal"; import RealmItself = Realm; export declare namespace Realm { export import Realm = RealmItself; export import flags = internal.flags; export import Object = internal.RealmObject; export import App = internal.App; export import Auth = internal.Auth; export import BSON = internal.BSON; export import Types = internal.Types; export import Services = internal.Services; export import index = internal.index; export import mapTo = internal.mapTo; export import kmToRadians = internal.kmToRadians; export import miToRadians = internal.miToRadians; export import AppChangeCallback = internal.AppChangeCallback; export import AppConfiguration = internal.AppConfiguration; export import AppServicesFunction = internal.AppServicesFunction; export import BaseConfiguration = internal.BaseConfiguration; export import BaseObjectSchema = internal.BaseObjectSchema; export import BaseSyncConfiguration = internal.BaseSyncConfiguration; export import CanonicalObjectSchema = internal.CanonicalObjectSchema; export import CanonicalPropertySchema = internal.CanonicalPropertySchema; export import CanonicalPropertiesTypes = internal.CanonicalPropertiesTypes; export import ClientResetMode = internal.ClientResetMode; export import ClientResetFallbackCallback = internal.ClientResetFallbackCallback; export import ClientResetBeforeCallback = internal.ClientResetBeforeCallback; export import ClientResetAfterCallback = internal.ClientResetAfterCallback; export import ClientResetManualConfiguration = internal.ClientResetManualConfiguration; export import ClientResetDiscardUnsyncedChangesConfiguration = internal.ClientResetDiscardUnsyncedChangesConfiguration; export import ClientResetRecoverUnsyncedChangesConfiguration = internal.ClientResetRecoverUnsyncedChangesConfiguration; export import ClientResetRecoverOrDiscardUnsyncedChangesConfiguration = internal.ClientResetRecoverOrDiscardUnsyncedChangesConfiguration; export import ClientResetConfig = internal.ClientResetConfig; export import CollectionChangeCallback = internal.CollectionChangeCallback; export import CollectionChangeSet = internal.CollectionChangeSet; export import CollectionPropertyTypeName = internal.CollectionPropertyTypeName; export import Collection = internal.Collection; export import CompensatingWriteError = internal.CompensatingWriteError; export import CompensatingWriteInfo = internal.CompensatingWriteInfo; export import ConfigurationWithoutSync = internal.ConfigurationWithoutSync; export import ConfigurationWithSync = internal.ConfigurationWithSync; export import Configuration = internal.Configuration; export import ConnectionNotificationCallback = internal.ConnectionNotificationCallback; export import ConnectionState = internal.ConnectionState; export import Credentials = internal.Credentials; export import DefaultFunctionsFactory = internal.DefaultFunctionsFactory; export import DefaultUserProfileData = internal.DefaultUserProfileData; export import Dictionary = internal.Dictionary; export import DictionaryChangeCallback = internal.DictionaryChangeCallback; export import DictionaryChangeSet = internal.DictionaryChangeSet; export import ErrorCallback = internal.ErrorCallback; export import FlexibleSyncConfiguration = internal.FlexibleSyncConfiguration; export import IndexDecorator = internal.IndexDecorator; export import List = internal.List; export import LocalAppConfiguration = internal.LocalAppConfiguration; export import MapToDecorator = internal.MapToDecorator; export import MetadataMode = internal.MetadataMode; export import Metadata = internal.Metadata; export import MigrationCallback = internal.MigrationCallback; export import Mixed = internal.Types.Mixed; export import NumericLogLevel = internal.NumericLogLevel; export import ObjectChangeCallback = internal.ObjectChangeCallback; export import ObjectChangeSet = internal.ObjectChangeSet; export import ObjectSchema = internal.ObjectSchema; export import ObjectType = internal.ObjectType; export import OpenRealmBehaviorConfiguration = internal.OpenRealmBehaviorConfiguration; export import OpenRealmBehaviorType = internal.OpenRealmBehaviorType; export import OpenRealmTimeOutBehavior = internal.OpenRealmTimeOutBehavior; export import OrderedCollection = internal.OrderedCollection; export import PartitionSyncConfiguration = internal.PartitionSyncConfiguration; export import PrimaryKey = internal.PrimaryKey; export import PrimitivePropertyTypeName = internal.PrimitivePropertyTypeName; export import ProgressDirection = internal.ProgressDirection; export import ProgressMode = internal.ProgressMode; export import ProgressNotificationCallback = internal.ProgressNotificationCallback; export import PropertiesTypes = internal.PropertiesTypes; export import PropertySchema = internal.PropertySchema; export import PropertySchemaParseError = internal.PropertySchemaParseError; export import PropertySchemaShorthand = internal.PropertySchemaShorthand; export import PropertySchemaStrict = internal.PropertySchemaStrict; export import PropertyTypeName = internal.PropertyTypeName; export import ProviderType = internal.ProviderType; export import ProxyType = internal.ProxyType; export import RealmEventName = internal.RealmEventName; export import RealmObjectConstructor = internal.RealmObjectConstructor; export import RelationshipPropertyTypeName = internal.RelationshipPropertyTypeName; export import Results = internal.Results; export import SchemaParseError = internal.SchemaParseError; export import SessionState = internal.SessionState; export import SessionStopPolicy = internal.SessionStopPolicy; export import Set = internal.RealmSet; export import SortDescriptor = internal.SortDescriptor; export import SSLConfiguration = internal.SSLConfiguration; export import SSLVerifyCallback = internal.SSLVerifyCallback; export import SSLVerifyObject = internal.SSLVerifyObject; export import SubscriptionSetState = internal.SubscriptionSetState; export import SyncConfiguration = internal.SyncConfiguration; export import SyncError = internal.SyncError; export import UpdateMode = internal.UpdateMode; export import UserChangeCallback = internal.UserChangeCallback; export import UserState = internal.UserState; export import User = internal.User; export import WaitForSync = internal.WaitForSync; export import GeoBox = internal.GeoBox; export import GeoCircle = internal.GeoCircle; export import GeoPoint = internal.GeoPoint; export import GeoPolygon = internal.GeoPolygon; export import CanonicalGeoPolygon = internal.CanonicalGeoPolygon; export import CanonicalGeoPoint = internal.CanonicalGeoPoint; export import GeoPosition = internal.GeoPosition; /** @deprecated Will be removed in v13.0.0. Please use {@link internal.AppServicesFunction} */ export import RealmFunction = internal.AppServicesFunction; /** @deprecated Will be removed in v13.0.0. Please use {@link internal.CanonicalPropertySchema} */ export import CanonicalObjectSchemaProperty = internal.CanonicalPropertySchema; /** @deprecated Will be removed in v13.0.0. Please use {@link internal.ClientResetRecoverUnsyncedChangesConfiguration} */ export import ClientResetRecoveryConfiguration = internal.ClientResetRecoverUnsyncedChangesConfiguration; /** @deprecated Will be removed in v13.0.0. Please use {@link internal.PropertySchema} */ export import ObjectSchemaProperty = internal.PropertySchema; /** @deprecated Will be removed in v13.0.0. Please use {@link internal.RealmObjectConstructor} */ export import ObjectClass = internal.RealmObjectConstructor; /** @deprecated Will be removed in v13.0.0. Please use {@link internal.PropertyTypeName} */ export import PropertyType = internal.PropertyTypeName; } export {};