Realm~App.Sync

Class for interacting with Atlas App Services.

Related Classes

AsyncOpenTask
AuthError
BaseSubscriptionSet
IncompatibleSyncedRealmError
MutableSubscriptionSet
Session
Subscription
SubscriptionSet
UserIdentity
Realm.App.Sync.SubscriptionsState
staticreadonly

Enum representing the state of a Realm.App.Sync.SubscriptionSet set.

Type:
"pending" or "complete" or "error" or "superseded"
Properties:
  • Pending
    • Type: "pending" or "complete" or "error" or "superseded"
    • Default: pending
    • The subscription update has been persisted locally, but the server hasn't yet returned all the data that matched the updated subscription queries.

  • Complete
    • Type: "pending" or "complete" or "error" or "superseded"
    • Default: complete
    • The server has acknowledged the subscription and sent all the data that matched the subscription queries at the time the SubscriptionSet was updated. The server is now in steady-state synchronization mode where it will stream updates as they come.

  • Error
    • Type: "pending" or "complete" or "error" or "superseded"
    • Default: error
    • The server has returned an error and synchronization is paused for this Realm. To view the actual error, use Subscriptions.error.

      You can still use Realm.App.Sync.SubscriptionSet#update to update the subscriptions, and if the new update doesn't trigger an error, synchronization will be restarted.

  • Superseded
    • Type: "pending" or "complete" or "error" or "superseded"
    • Default: superseded
    • The SubscriptionSet has been superseded by an updated one. This typically means that someone has called Realm.App.Sync.SubscriptionSet#update on a different instance of the Subscriptions. You should not use a superseded SubscriptionSet, and instead obtain a new instance from Realm.subscriptions.

Realm.App.Sync._hasExistingSessions(app)
static

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.

Parameters:
  • app optional
    • Type: Realm.App
    • The app where the Realm was opened.

Realm.App.Sync.enableSessionMultiplexing(app)
static

Enable multiplexing multiple sync sessions over a single connection for a Realm app. When having a lot of synchronized realms open the system might run out of file descriptors because of all the open sockets to the server. Session multiplexing is designed to alleviate that, but it might not work with a server configured with fail-over. Only use if you're seeing errors about reaching the file descriptor limit and you know you are using many sync sessions.

Parameters:
Realm.App.Sync.getAllSyncSessions(user)[Realm.App.Sync.Session, ...]
static

Returns all sync sessions for a user.

Parameters:
Returns: [Realm.App.Sync.Session, ...] an array of sessions
Realm.App.Sync.getSyncSession(user, partitionValue)Realm.App.Sync.Session
static

Returns the session associated with a user and partition value.

Parameters:
  • partitionValue
    • Type: string or number or ObjectId or null
Returns: Realm.App.Sync.Session the session
Realm.App.Sync.initiateClientReset(app, path)
staticDeprecated

Initiate a client reset. The Realm must be closed prior to the reset.

A synced Realm may need to be reset if the communications with the Atlas Device Sync Server indicate an unrecoverable error that prevents continuing with normal synchronization. The most common reason for this is if a client has been disconnected for too long.

The local copy of the Realm is moved into a recovery directory for safekeeping.

Local writes that were not successfully synchronized to Atlas will be present in the local recovery copy of the Realm file. The re-downloaded Realm will initially contain only the data present at the time the Realm was synchronized up on the server.

Parameters:
  • app optional
    • Type: Realm.App
    • The app where the Realm was opened.

  • path optional
    • Type: string
    • The path to the Realm to reset. Throws error if reset is not possible.

Example:
{
  // Once you have opened your Realm, you will have to keep a reference to it.
  // In the error handler, this reference is called `realm`
  const config = {
    // schema, etc.
    sync: {
      user,
      partitionValue,
      error: (session, error) => {
        if (error.name === 'ClientReset') {
          let path = realm.path; // realm.path will no be accessible after realm.close()
          realm.close();
          Realm.App.Sync.initiateClientReset(app, path);
          // - open Realm at `error.config.path` (oldRealm)
          // - open Realm with `config` (newRealm)
          // - copy required objects from oldRealm to newRealm
          // - close both Realms
        }
      }
    }
  };
}
Realm.App.Sync.reconnect(app)
static

Calling this method will force Realm to attempt to reconnect the Realm App to the server immediately.

Realm will reconnect automatically, but by using exponential backoff. This means that if the device is offline for a long time, restoring the connection after it comes back online can take longer than expected. In situations where it is possible to detect the network condition (e.g. Airplane mode). Manually calling this method can provide a smoother user experience.

Parameters:
Realm.App.Sync.setLogger(app, logger)
static

Capture the sync client's log. You can only set the log level once, and you must do it after creating an App instance but before opening any Realms.

See: {Realm.App.Sync~setLogLevel}
Parameters:
Example:
{
const app = new Realm.App(getAppConfig());
Realm.App.Sync.setLogger(app, (level, message) => console.log(`[${level}] ${message}`));
const user = await app.logIn(credentials);
const realm = await Realm.open(getRealmConfig(user));
}
Realm.App.Sync.setLogLevel(app, level)
static

Set the sync log level. You can only set the log level once, and you must do it after creating an App instance but before opening any Realms.

Parameters:
  • level
Example:
{
const app = new Realm.App(getAppConfig());
Realm.App.Sync.setLogLevel(app, "all");
const user = await app.logIn(credentials);
const realm = await Realm.open(getRealmConfig(user));
}
Realm.App.Sync.setUserAgent(app, userAgent)
static

Set the application part of the User-Agent string that will be sent to the Realm Object Server when a session is created.

This method can only be called up to the point where the first Realm is opened. After that, the User-Agent can no longer be changed.

Parameters:
  • userAgent
    • Type: string
    • the user agent description

ClientResetConfiguration

This describes the options to configure client reset.

Type:
Object
Properties:
  • mode
    • Type: string
    • Either "manual" (deprecated, see also Realm.App.Sync.initiateClientReset()) or "discardLocal" (download a fresh copy from the server).

  • clientResetBefore optional
    • Type: callback(realm) or null
    • called before sync initiates a client reset.

  • clientResetAfter optional
    • Type: callback(beforeRealm, afterRealm) or null
    • called after client reset has been executed; beforeRealm and afterRealm are instances of the Realm before and after the client reset.

downloadBeforeOpenBehavior

The default behavior settings if you want to wait for downloading a synchronized Realm to complete before opening it.

InitialSubscriptionsConfiguration

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, Realm.open will not resolve until this set of subscriptions has been fully synchronized with the server.

Example:

const config: Realm.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 synchronized.
Type:
Object
Properties:
  • update
    • Type: callback(realm)
    • callback called with a Realm.App.Sync~MutableSubscriptionSet instance and the Realm instance to allow you to setup the initial set of subscriptions. See Realm.App.Sync.SubscriptionSet#update for more information.

  • rerunOnOpen
    • Type: Boolean
    • optional flag. If true, the 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.

logCallback(level, message)

A callback passed to Realm.App.Sync.setLogger when instrumenting the Atlas Device Sync client with a custom logger.

Parameters:
  • level
    • Type: number
    • 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.

  • message
    • Type: string
    • The message of the log entry.

LogLevel
Type:
"all" or "trace" or "debug" or "detail" or "info" or "warn" or "error" or "fatal" or "off"
openLocalRealmBehavior

The default behavior settings if you want to open a synchronized Realm immediately and start working on it. If this is the first time you open the Realm, it will be empty while the server data is being downloaded in the background.

OpenRealmBehaviorConfiguration

Specify how to open a synced Realm.

Type:
Object
Properties:
  • type
    • Type: string
    • how to open a Realm - 'downloadBeforeOpen' to wait for download to complete or 'openImmediately' to open the local Realm

  • timeOut optional
    • Type: number
    • how long to wait for a download (in ms). Default: infinity

  • timeOutBehavior optional
    • Type: string
    • what to do when download times out - 'openLocalRealm' to open the local Realm or 'throwException' to throw an exception.

ProviderType

The type of an authentication provider, used to authenticate a user.

Type:
"anon-user" or "api-key" or "local-userpass" or "custom-function" or "custom-token" or "oauth2-google" or "oauth2-facebook" or "oauth2-apple"
SSLConfiguration

This describes the different options used to create a Realm instance with Atlas Device Sync.

Type:
Object
Properties:
  • validate
    • Type: boolean
    • Indicating if SSL certificates must be validated. Default is true.

  • certificatePath
    • Type: string
    • A path where to find trusted SSL certificates.

  • validateCallback
    • Type: sslValidateCallback
    • A callback function used to accept or reject the server's SSL certificate.

Realm.App.Sync.SubscriptionOptions

Options for Realm.App.Sync.SubscriptionSet.add

Type:
Object
Properties:
  • throwOnUpdate
    • Type: boolean or undefined
    • By default, adding a subscription with the same name as an existing one but a different query will update the existing subscription with the new query. If throwOnUpdate is set to true, adding a subscription with the same name but a different query will instead throw an exception. Adding a subscription with the same name and query is always a no-op.

SyncConfiguration

This describes the different options used to create a Realm instance with Atlas App Services synchronization.

Type:
Object
Properties:
  • flexible
    • Type: boolean
    • Whether to use flexible sync (if true) or partition based sync (default)

  • partitionValue
    • Type: string or number or BSON.ObjectId or null
    • The value of the partition key. Only valid if using partition based sync.

  • error optional
    • Type: callback(session, syncError)
    • A callback function which is called in error situations. The callback is passed two arguments: session and syncError. If syncError.name == "ClientReset", syncError.path and syncError.config are set and syncError.readOnly is true (deprecated, see Realm.App.Sync~ClientResetConfiguration). Otherwise, syncError can have up to five properties: name, message, isFatal, category, and code.

  • customHttpHeaders optional
    • Type: Object
    • A map (string, string) of custom HTTP headers.

  • newRealmFileBehavior optional
    • Type: OpenRealmBehaviorConfiguration
    • Whether to create a new file and sync in background or wait for the file to be synced. If not set, the Realm will be downloaded before opened.

  • existingRealmFileBehavior optional
    • Type: OpenRealmBehaviorConfiguration
    • Whether to open existing file and sync in background or wait for the sync of the file to complete and then open. If not set, the Realm will be downloaded before opened.