Cuando usas Atlas Device Sync, el SDK de Node.js sincroniza datos con Atlas en segundo plano mediante una sesión de sincronización. Una sesión de sincronización comienza cada vez que abres un realm sincronizado.
Requisitos previos
Before you can manage a sync session, you must perform the following:
Acceder a la sesión de sincronización
Después de abrir un reino sincronizado, puedes acceder a su sesión de sincronización con el Propiedad Realm.syncSession.
const realm = await Realm.open(config); const syncSession = realm.syncSession;
Pause or Resume a Sync Session
Al abrir un reino sincronizado, se inicia una sesión de sincronización. Puedes pausar y reanudar la sesión de sincronización en ese reino. Pausar una sesión de sincronización solo pausa la sesión de sincronización de ese reino. Si tienes más de un reino abierto, la pausa no afecta las sesiones de sincronización de los demás reinos.
Para pausar la sincronización, utilice el método syncSession.pause(). Para reanudarla, utilice el método syncSession.resume().
const behaviorConfiguration = { type: "openImmediately", }; const config = { schema: [DogSchema], sync: { user: app.currentUser, partitionValue: "MyPartitionValue", newRealmFileBehavior: behaviorConfiguration, existingRealmFileBehavior: behaviorConfiguration, }, }; const realm = await Realm.open(config); const pauseSyncSession = () => { realm.syncSession?.pause(); }; const resumeSyncSession = () => { realm.syncSession?.resume(); };
const behaviorConfiguration: Realm.OpenRealmBehaviorConfiguration = { type: Realm.OpenRealmBehaviorType.OpenImmediately, }; const config: Realm.Configuration = { schema: [DogSchema], sync: { user: app.currentUser!, partitionValue: "MyPartitionValue", newRealmFileBehavior: behaviorConfiguration, existingRealmFileBehavior: behaviorConfiguration, }, }; const realm = await Realm.open(config); const pauseSyncSession = () => { realm.syncSession?.pause(); }; const resumeSyncSession = () => { realm.syncSession?.resume(); };
Cuándo pausar una sesión de sincronización
For most applications, there is no need to manually pause and resume a sync session. However, there are a few circumstances under which you may want to pause or suspend a sync session:
You only want to sync after the user takes a specific action
You only want to sync during a certain time of the day
No debes intentar sincronizar cuando hay una mala conectividad de red
You want to explicitly force a sync session to connect
In the case of poor network connectivity, continually trying to establish a network connection can drain the user's device battery.
The case of explicitly forcing a sync session to connect is most commonly related to being offline for some time. The sync client attempts to connect, and upon failure, goes into exponential backoff. After being offline for a long time, the client may not immediately reconnect. Pausing and resuming the sync session explicitly forces the connection.
When you do pause a sync session, keep these things in mind:
If the client may be offline longer than the client maximum offline time, the client will be unable to resume syncing and must perform a client reset.
Pausing a sync session pauses it in both directions. Changes that your app makes on the device do not sync with the backend, and changes to the data in the backend or on other devices do not sync to the device. There is no way to pause only uploads or pause only downloads.
No pause una sesión de sincronización si desea que un cliente deje de sincronizarse permanentemente con el backend. Para ello, copie el contenido del dominio sincronizado en uno no sincronizado y utilice este último en el cliente.
No pauses la sincronización para detener la sincronización por períodos de tiempo indefinidos o rangos de meses y años. La funcionalidad no está diseñada ni probada para estos casos de uso. Podrías encontrar un rango de problemas al usarlo de esta manera.
Wait for Upload and Download
To asynchronously wait for all changes to upload to Atlas from your synced realm, call uploadAllLocalChanges(). This method returns true when all changes have been uploaded.
realm.write(() => { realm.create(Doggie, { _id: new BSON.ObjectID(), owner_id: app.currentUser!.id, name: "Maui", age: 3, }); }); await realm.syncSession?.uploadAllLocalChanges();
To asynchronously wait for all changes on Atlas to download from the Device Sync server to your synced realm, call downloadAllServerChanges(). This method returns true when all changes have been downloaded.
await realm.syncSession?.downloadAllServerChanges();
Puede especificar un tiempo de espera de solicitud en la configuración de la aplicación. Con un tiempo de espera especificado, puede configurar
cancelWaitsOnNonFatalErrors En su BaseSyncConfiguration. Cuando true y el intervalo de tiempo de espera se alcanzan, cualquier trabajo pendiente que esté pendiente de cargas y descargas se cancela. Si esta configuración es falsa, la espera de cargas y descargas no se cancela, ya que Realm trata estos tiempos de espera como errores no fatales.
Para obtener más información, revisa Configura un tiempo de espera para la aplicación cliente y Cancela operaciones asíncronas después de un tiempo de espera.
Consulta el progreso de carga y descarga para una sesión de sincronización
Para verificar el progreso de carga y descarga de una sesión de sincronización, agregue una notificación de progreso usando el método syncSession.addProgressNotification().
El método syncSession.addProgressNotification() toma los siguientes tres parámetros:
Un parámetro
direction. Ajuste en"upload"para registrar notificaciones de carga de datos. Establécelo en"download"para registrar notificaciones al descargar datos.A
modeparameter. Set to"reportIndefinitely"for the notifications to continue until the callback is unregistered using syncSession.removeProgressNotification(). Set to"forCurrentlyOutstandingWork"for the notifications to continue until only the currently transferable bytes are synced.A callback function parameter that has the arguments
transferredandtransferable.transferredis the current number of bytes already transferred.transferableis the total number of bytes already transferred plus the number of bytes pending transfer.
Nota
Flexible Sync progress notifications are not yet fully supported. When using Flexible Sync, downloads only report notifications after changes are integrated. Partition-Based Sync provides ongoing notifications as changes progress downloading. Uploads report ongoing progress notifications for both Sync Modes.
Ejemplo
In the following example, an application developer registers a callback on the syncSession to listen for upload events indefinitely. The developer writes to the realm and then unregisters the syncSession notification callback.
const behaviorConfiguration = { type: "openImmediately", }; const config = { schema: [DogSchema], sync: { user: app.currentUser, partitionValue: "MyPartitionValue", newRealmFileBehavior: behaviorConfiguration, existingRealmFileBehavior: behaviorConfiguration, }, }; const realm = await Realm.open(config); const handleNotifcationRemoval = (transferred, transferable) => { console.log(`There were ${transferable} transferable bytes total.`); console.log(`${transferred} bytes were transferred.`); }; const handleNotifications = (transferred, transferable) => { if (transferred === transferable) { console.log( `${transferred} bytes of ${transferable} were transferred.` ); // Remove progress notification. realm.syncSession?.removeProgressNotification(handleNotifcationRemoval); } }; realm.syncSession?.addProgressNotification( "upload", "reportIndefinitely", handleNotifications ); // Upload a Realm object. const dog = realm.write(() => { return realm.create("Dog", { _id: new Realm.BSON.ObjectID(), MyPartitionValue: "MyPartitionValue", name: "Fido", age: 2, }); });
const behaviorConfiguration: Realm.OpenRealmBehaviorConfiguration = { type: Realm.OpenRealmBehaviorType.OpenImmediately, }; const config: Realm.Configuration = { schema: [DogSchema], sync: { user: app.currentUser!, partitionValue: "MyPartitionValue", newRealmFileBehavior: behaviorConfiguration, existingRealmFileBehavior: behaviorConfiguration, }, }; const realm = await Realm.open(config); const handleNotifcationRemoval = ( transferred: number, transferable: number ) => { console.log(`There were ${transferable} transferable bytes total.`); console.log(`${transferred} bytes were transferred.`); }; const handleNotifications = (transferred: number, transferable: number) => { if (transferred === transferable) { console.log( `${transferred} bytes of ${transferable} were transferred.` ); // Remove progress notification. realm.syncSession?.removeProgressNotification(handleNotifcationRemoval); } }; realm.syncSession?.addProgressNotification( Realm.ProgressDirection.Upload, Realm.ProgressMode.ReportIndefinitely, handleNotifications ); // Upload a Realm object. const dog = realm.write(() => { return realm.create("Dog", { _id: new Realm.BSON.ObjectID(), MyPartitionValue: "MyPartitionValue", name: "Fido", age: 2, }); });
Check the Network Connection
Para comprobar el estado actual de la conexión al servidor, llame al método syncSession.connectionState().
El diseño offline-first de Realm significa que generalmente no es necesario verificar el estado actual de la conexión de red. Dicho esto, el método syncSession.connectionState() está disponible si su aplicación necesita obtener el estado actual de la conexión con el servidor.
const config = { schema: [DogSchema], sync: { user: app.currentUser, partitionValue: "MyPartitionValue", }, }; const realm = await Realm.open(config); const connectionState = realm.syncSession?.connectionState;
const config: Realm.Configuration = { schema: [DogSchema], sync: { user: app.currentUser!, partitionValue: "MyPartitionValue", }, }; const realm = await Realm.open(config); const connectionState = realm.syncSession?.connectionState;
Sesiones de sincronización multiplex
Habilitar multiplexación de sesiones Para consolidar varias sesiones de sincronización de una aplicación Realm. Utilice la multiplexación de sesiones solo si detecta errores al alcanzar el límite de descriptores de archivo y sabe que está utilizando muchas sesiones de sincronización.
To enable session multiplexing, call Realm.App.Sync.enableSessionMultiplexing() with your Realm.App.
Ejemplo
Realm.App.Sync.enableSessionMultiplexing(app);