La Partition-Based Sync es una moda más antigua para utilizar Atlas Device Sync con el Realm React Native SDK. Recomendamos usar Flexible Sync para nuevas aplicaciones. La información en esta página es para usuarios que aún utilizan Partition-Based Sync.
Para obtener más información sobre la sincronización basada en particiones y cómo configurarla en Atlas App Services, consulte Sincronización basada en particiones en la documentación de App Services.
valor de la partición
Cuando se selecciona Partition-Based Sync para la configuración de la aplicación de backend, la implementación del cliente debe incluir un valor de la partición. Este es el valor del campo clave de partición que se selecciona al configurar la Partition-Based Sync.
El valor de la partición determina a qué datos puede acceder la aplicación cliente.
You pass in the partition value when you open a synced realm.
Configure a Partition-Based Sync Realm
Para abrir un reino de sincronización flexible, use @realm/reactLa función createRealmContext() y su valor devuelto RealmProvider.
En un RealmProvider que esté anidado en un UserProvider, agrega una propiedad sync con un objeto SyncConfiguration que contenga flexible: true.
Note that UserProvider automatically passes an authenticated user to RealmProvider.
<RealmProvider schema={[YourObjectModel]} sync={{ partitionValue: 'testPartition', }}> <RestOfApp /> </RealmProvider>
Copiar datos y abrir un nuevo Realm
New in version realm@10.14.0.
To copy data from an existing realm to a new realm with different configuration options, pass the new configuration the Realm.writeCopyTo() method.
Nota
Solo sincronización de mismo tipo
This method only supports copying a Partition-Based Sync configuration for another Partition-Based Sync user, or a Flexible Sync configuration for another Flexible Sync user. You cannot use this method to convert between a Partition-Based Sync realm and a Flexible Sync realm or vice-versa.
In the new realm's configuration, you must specify the path.
If you write the copied realm to a realm file that already exists, the data is written object by object. The copy operation replaces objects if there already exists objects for given primary keys. The schemas of the realm you copy and the realm you are writing to must be compatible for the copy operation to succeed. Only objects in the schemas of both configurations are copied over.
El cambio de configuración puede incluir modificaciones en SyncConfiguration:
Local realm to synced realm
Synced Realm to local realm
The configuration change can also include changes to encryptionKey property of the Configuration:
Encrypted realm to unencrypted realm
Unencrypted realm to encrypted realm
Ejemplo
Convert Local Realm to Synced Realm
const localConfig = { schema: [Car], path: "localOnly.realm", }; const localRealm = await Realm.open(localConfig); const syncedConfig = { schema: [Car], path: "copyLocalToSynced.realm", sync: { user: app.currentUser, partitionValue: "myPartition", }, }; localRealm.writeCopyTo(syncedConfig); const syncedRealm = await Realm.open(syncedConfig);
const localConfig: Realm.Configuration = { schema: [Car], path: "localOnly.realm", }; const localRealm = await Realm.open(localConfig); const syncedConfig: Realm.Configuration = { schema: [Car], path: "copyLocalToSynced.realm", sync: { user: app.currentUser!, partitionValue: "myPartition", }, }; localRealm.writeCopyTo(syncedConfig); const syncedRealm = await Realm.open(syncedConfig);
You can also combine changes to configuration. For example, you can open a local encrypted realm as a synced unencrypted realm or a unencrypted synced realm as an encrypted synced realm.
Ejemplo
Convert Synced Encrypted to Local Unencrypted Realm
// Create a secure key. const encryptionKey = new Int8Array(64); // ... store key const syncedEncryptedConfig = { schema: [Car], path: "syncedEncrypted.realm", sync: { user: app.currentUser, partitionValue: "myPartition", }, encryptionKey, }; const syncedEncryptedRealm = await Realm.open(syncedEncryptedConfig); const localUnencryptedConfig = { schema: [Car], path: "copyLocalUnencrypted.realm", }; syncedEncryptedRealm.writeCopyTo(localUnencryptedConfig); const localUnencryptedRealm = await Realm.open(syncedEncryptedConfig);
// Create a secure key. const encryptionKey = new Int8Array(64); // ... store key const syncedEncryptedConfig: Realm.Configuration = { schema: [Car], path: "syncedEncrypted.realm", sync: { user: app.currentUser!, partitionValue: "myPartition", }, encryptionKey, }; const syncedEncryptedRealm = await Realm.open(syncedEncryptedConfig); const localUnencryptedConfig: Realm.Configuration = { schema: [Car], path: "copyLocalUnencrypted.realm", }; syncedEncryptedRealm.writeCopyTo(localUnencryptedConfig); const localUnencryptedRealm = await Realm.open(syncedEncryptedConfig);
Migrate from Partition-Based Sync to Flexible Sync
Puedes migrar tu App Services Device Sync Mode de Partition-Based Sync a Flexible Sync. La migración es un proceso automático que no requiere ningún cambio en el código de tu aplicación. La migración automática requiere la versión 11.10.0 o superior del SDK de Realm Node.js.
Migrating enables you to keep your existing App Services users and authentication configuration. Flexible Sync provides more versatile permissions configuration options and more granular data synchronization.
For more information about how to migrate your App Services App from Partition-Based Sync to Flexible Sync, refer to Migrate Device Sync Modes.
Actualizar el código de cliente después de la migración
The automatic migration from Partition-Based Sync to Flexible Sync does not require any changes to your client code. However, to support this functionality, Realm automatically handles the differences between the two Sync Modes by:
Automatically creating Flexible Sync subscriptions for each object type where
partitionKey == partitionValue.Inyectar un campo
partitionKeyen cada objeto si aún no existe uno. Esto es necesario para la suscripción automática de Flexible Sync.
Si necesitas realizar actualizaciones en el código cliente después de la migración, considera actualizar tu base de código cliente para remover funcionalidades ocultas de migración. Tal vez quieras actualizar tu base de código de cliente cuando:
Agregue un nuevo modelo o cambie un modelo en su base de código de cliente.
You add or change functionality that involves reading or writing Realm objects
Quieres implementar un control más específico sobre los datos que sincronizas
Make these changes to convert your Partition-Based Sync client code to use Flexible Sync:
Agregue
flexible:truea su objeto SyncConfiguration donde abra un Realm sincronizado.Agrega propiedades relevantes a tus modelos de objetos para usarlas en tus suscripciones de Flexible Sync. Por ejemplo, podrías agregar una propiedad
ownerIdpara permitir que un usuario sincronice solo sus propios datos.Remove automatic Flexible Sync subscriptions and manually create the relevant subscriptions.
For examples of Flexible Sync permissions strategies, including examples of how to model data for these strategies, refer to Device Sync Permissions Guide.
Remove and Manually Create Subscriptions
When you migrate from Partition-Based Sync to Flexible Sync, Realm automatically creates hidden Flexible Sync subscriptions for your app. The next time you add or change subscriptions, we recommend that you:
Esto le permite ver toda su lógica de suscripción junta en su base de código para futuras iteraciones y depuraciones.
For more information about the automatically-generated Flexible Sync subscriptions, refer to Migrate Client App to Flexible Sync.