同期された Realm
Realm を構成して、それぞれがデータのローカル コピーを持つ多数のデバイス間でデータを自動的に同期できます。 同期された Realm はローカル専用の Realm とは異なる構成を使用するため、同期プロセスを処理するには Atlas App Services バックエンド が必要です。
アプリケーションは、オフラインでも、ローカルで同期された Realm オブジェクトをいつでも作成、変更、削除できます。 ネットワーク接続が利用可能になるたびに、Realm SDK はアプリケーション サーバーへの接続を開き、他のクライアントとの間での変更を同期します。 Atlas Device Sync プロトコルとサーバー側の運用変換では、特定の変更がオフラインで発生したり、正しい順序で受信されなかった場合でも、Realm の完全に同期されたすべてのインスタンスが完全に同じデータを参照することが保証されます。
前提条件
Node.js アプリケーションで Flexible Sync を使用して Realm を構成する前に、
バックエンド で Flexible Sync を有効にします。 Flexible Sync は、クライアント アプリケーションで使用する前に、バックエンドで構成する必要があります。
クライアント プロジェクトでユーザーを認証します。
同期された Realm を開く
Device Sync を実装する最初のステップは、同期された Realm を開くことです。 以下の情報は、Flexible Sync を使用するアプリに関連します。 既存のアプリが古いパーティションベースの同期を使用している場合は、「パーティションベースの同期 Realm を開く」を参照してください。 どれを使用するかをまだ決定していない、または不明な場合は、[同期モードの選択 ] ページをお読みください。
Flexible Sync を使用して Realm を開くには、 Realm.open()を呼び出します。 ConfigurationWithSyncオブジェクトを渡します。このオブジェクトには、 SyncConfigurationオブジェクトを定義する syncプロパティが含まれている必要があります。 同期構成では、 userとflexible:trueを含める必要があります。
const realm = await Realm.open({ schema: [TaskSchema, TeamSchema], sync: { user: app.currentUser, flexible: true, }, });
デフォルトでは、Realm は返す前にサーバーからのすべてのデータを同期します。 バックグラウンドでデータを同期する場合は、 「 オフライン時に同期された Realm を開く」セクションをお読みください。
重要
Flexible Sync にはサブスクリプションが必要
少なくとも 1 つのサブスクリプションを追加するまで、Flexible Sync レルムは使用できません。 サブスクリプションを追加する方法については、「サブスクリプションの追加 」を参照してください。
特定のパスで同期された Realm を開く
バージョンrealm@11.6.0の新機能。
AppConfiguration.baseFilePathとRealm.Configuration.pathを使用することで、 Realm ファイルとメタデータ ファイルをクライアント デバイスに保存する場所を制御できます。
そのためには、 <AppProvider>.baseFilePathを設定します。 baseFilePathが設定されていない場合は、現在のワークディレクトリが使用されます。 より制御するために<RealmProvider>.sync.pathを設定することもできます。
const app = new Realm.App({ id: APP_ID, baseFilePath: customPath }); const user = await app.logIn(Realm.Credentials.anonymous()); const realm = await Realm.open({ schema: [Car], sync: { flexible: true, user, }, });
baseFilePathが設定されている場合、メタデータは常に<baseFilePath>/mongodb-realm/に保存されます。 baseFilePathが設定されていない場合、メタデータは<Realm.defaultPath>/mongodb-realmに保存されます。
Realm ファイルが正確に保存される場所は、 Realm.Configuration.pass の設定方法によって異なる場合があります。
Realm.Configuration.pathは設定されておらず、baseFilePathが設定されています。 Your Realm file is stored atbaseFilePath.Realm.Configuation.pathは相対パスに設定されています。 Realm ファイルはbaseFilePathを基準に保存されます。Realm.Configuration.pathは、絶対パスです。 Realm ファイルはRealm.Configuration.pathに保存されています。
オフライン時に同期された Realm を開く
Realm アプリケーションはユーザーを認証する際、ユーザーの認証情報をキャッシュします。 既存のユーザー認証情報を確認して、ログイン フローをバイパスし、キャッシュされたユーザーにアクセスできます。 これを使用して、Realm をオフラインで開きます。
注意
最初のログインにはネットワーク接続が必要です
ユーザーがアプリにサインアップしたり、クライアントに既存のアカウントを使用して初めてログインする場合、クライアントにはネットワーク接続が必要です。 キャッシュされたユーザー認証情報を確認すると、ユーザーが以前にオンライン時にログインしたことがある場合にのみ、オフラインで Realm を開くことができます。
// Log user into your App Services App. // On first login, the user must have a network connection. const getUser = async () => { // If the device has no cached user credentials, log in. if (!app.currentUser) { const credentials = Realm.Credentials.anonymous(); await app.logIn(credentials); } // If the app is offline, but credentials are // cached, return existing user. return app.currentUser!; };
次のサブセクションでは、バックグラウンド同期を使用してオフラインのときに Realm にアクセスする方法を示します。 これを行うには、キャッシュされたユーザーとOpenRealmBehaviorConfigurationオブジェクトを使用します。
同期構成内で、オプションのnewRealmFileBehavior existingRealmFileBehaviorフィールドと フィールドをOpenRealmBehaviorConfiguration オブジェクトに設定して、バックグラウンド同期を有効にします。
重要
オフライン ログインは柔軟な同期構成とパーティションベースの同期構成の両方でサポートされています
バックグラウンド同期を使用してすぐに、またはタイムアウトが経過した後に Flexible Sync または古い パーティションベースの同期 を使用してRealmを開くことができます。
パーティションベースの同期 は、廃止された同期モードです。 アプリケーションで パーティションベースの同期 を使用する方法の詳細については、「パーティションベースの同期 - Node.js SDK 」ページを参照してください。
バックグラウンド同期ですぐに開く
ユーザーのデバイスがインターネットに接続されていない場合、または接続状態が不明な場合は、Realm 動作のタイプをopenImmediatelyに設定します。 これにより、バックグラウンドでサーバーからのデータが同期されます。
const behaviorConfiguration = { type: "openImmediately", }; const config = { schema: [Car], sync: { user: await getUser(), flexible: true, newRealmFileBehavior: behaviorConfiguration, existingRealmFileBehavior: behaviorConfiguration, }, }; const realm = await Realm.open(config);
const behaviorConfiguration: Realm.OpenRealmBehaviorConfiguration = { type: "openImmediately", }; const config: Realm.Configuration = { schema: [Car], sync: { user: await getUser(), flexible: true, newRealmFileBehavior: behaviorConfiguration, existingRealmFileBehavior: behaviorConfiguration, }, }; const realm = await Realm.open(config);
バックグラウンド同期でタイムアウト後に開く
データを同期したいが、ユーザーがインターネットに接続しているかどうかが不明な環境にある場合は、 timeOutを指定します。 これにより、次のいずれかの場合にRealmが自動的に開きます。
タイムアウト期間が経過した
Realm が完全にダウンロードされました。
Realm がタイムアウト前にダウンロードを完了しない場合、最初の Realm 同期はバックグラウンドで続行されます。
const behaviorConfiguration = { type: "openImmediately", timeOut: 1000, timeOutBehavior: "openLocalRealm", }; const config = { schema: [Car], sync: { flexible: true, user: await getUser(), existingRealmFileBehavior: behaviorConfiguration, newRealmFileBehavior: behaviorConfiguration, }, }; const realm = await Realm.open(config);
const behaviorConfiguration: Realm.OpenRealmBehaviorConfiguration = { type: "openImmediately", timeOut: 1000, timeOutBehavior: "openLocalRealm", }; const config: Realm.Configuration = { schema: [Car], sync: { flexible: true, user: await getUser(), existingRealmFileBehavior: behaviorConfiguration, newRealmFileBehavior: behaviorConfiguration, }, }; const realm = await Realm.open(config);
バックグラウンドでの変更の同期
同期された Realm がサーバーからデータをダウンロードする間にユーザーに部分的なデータを表示するために、バックグラウンドで変更を同期してユーザー エクスペリエンスがブロックされるのを防ぐ場合があります。 ユーザーのデバイスがオフラインになる可能性があるアプリケーションでは、バックグラウンドで変更を同期することをお勧めしGo 。 バックグラウンドで変更を同期するには、同期された Realm を同期的に開きます。
OpenRealmBehaviorConfigurationオブジェクトを作成し、そのtypeを"openImmediately"に設定します。
const behaviorConfiguration = { type: "openImmediately", };
const behaviorConfiguration: Realm.OpenRealmBehaviorConfiguration = { type: Realm.OpenRealmBehaviorType.OpenImmediately, };
構成オブジェクトを作成します。このオブジェクトには、 SyncConfigurationオブジェクトを定義するsyncプロパティが含まれている必要があります。 このOpenRealmBehaviorConfiguration オブジェクトをnewRealmFileBehavior existingRealmFileBehaviorの フィールドとSyncConfiguration フィールドの値として設定します。
const config = { schema: [DogSchema], sync: { user: app.currentUser, partitionValue: "MyPartitionValue", // The behavior to use when this is the first time opening a realm. newRealmFileBehavior: behaviorConfiguration, // The behavior to use when a realm file already exists locally, // i.e. you have previously opened the realm. existingRealmFileBehavior: behaviorConfiguration, }, };
const config: Realm.Configuration = { schema: [DogSchema], sync: { user: app.currentUser!, partitionValue: "MyPartitionValue", // The behavior to use when this is the first time opening a realm. newRealmFileBehavior: behaviorConfiguration, // The behavior to use when a realm file already exists locally, // i.e. you have previously opened the realm. existingRealmFileBehavior: behaviorConfiguration, }, };
最後に、 Realm.open()を呼び出して、同期された Realm を開きます。 これにより、同期セッションが作成され、バックグラウンドでサーバーから既存のデータのダウンロードが開始されます。
const realm = await Realm.open(config);
タイムアウト後に非同期操作をキャンセルする
バージョン 12.0.0 の新機能。
baseSyncConfigurationオブジェクトでcancelWaitsOnNonFatalErrorsプロパティを指定できます。
trueの場合、Node.js SDK は、タイムアウト期間が経過すると、アップロードやダウンロードの待機などの非同期操作をキャンセルします。 AppConfigurationでこのオプションのタイムアウトを定義できます。 例については、「 アプリ クライアントのタイムアウトの構成 」を参照してください。
このプロパティは、値を指定しない場合、デフォルトでfalseになります。
const config = { schema: [Doggie], sync: { flexible: true, user: app.currentUser, // When `true`, upload and download waits are canceled on any // error, such as a timeout, instead of just a fatal error. // You can provide an optional timeouts property in milliseconds. cancelWaitsOnNonFatalError: true, }, };
const config: Realm.Configuration = { schema: [Doggie], sync: { flexible: true, user: app.currentUser!, // When `true`, upload and download waits are canceled on any // error, such as a timeout, instead of just a fatal error. // You can provide an optional timeouts property in milliseconds. cancelWaitsOnNonFatalError: true, }, };