### RxDB Workflow Example Source: https://rxdb.info/articles/alternatives/nedb-alternative.html Illustrates the equivalent workflow in RxDB, including database creation, collection setup, insertion, and querying. ```javascript import { createRxDatabase } from 'rxdb/plugins/core'; import { getRxStorageLocalstorage } from 'rxdb/plugins/storage-localstorage'; const db = await createRxDatabase({ name: 'tasks', storage: getRxStorageLocalstorage() }); await db.addCollections({ tasks: { schema: { title: 'task schema', version: 0, primaryKey: 'id', type: 'object', properties: { id: { type: 'string', maxLength: 100 }, title: { type: 'string' }, done: { type: 'boolean' } }, required: ['id', 'title', 'done'] } } }); await db.tasks.insert({ id: 't1', title: 'Write report', done: false }); const openTasks = await db.tasks .find({ selector: { done: false }, sort: [{ title: 'asc' }] }) .exec(); ``` -------------------------------- ### RxDB Quick Example with Local Storage Source: https://rxdb.info/articles/reactjs-storage.html Sets up an RxDB database using local storage, adds a collection, and inserts/queries documents. This is a basic setup for offline-first applications. ```javascript import { createRxDatabase } from 'rxdb'; import { getRxStorageLocalstorage } from 'rxdb/plugins/storage-localstorage'; (async function setUpRxDB() { const db = await createRxDatabase({ name: 'heroDB', storage: getRxStorageLocalstorage(), multiInstance: false }); const heroSchema = { title: 'hero schema', version: 0, type: 'object', primaryKey: 'id', properties: { id: { type: 'string', maxLength: 100 }, name: { type: 'string' }, power: { type: 'string' } }, required: ['id', 'name'] }; await db.addCollections({ heroes: { schema: heroSchema } }); // Insert a doc await db.heroes.insert({ id: '1', name: 'AlphaHero', power: 'Lightning' }); // Query docs once const allHeroes = await db.heroes.find().exec(); console.log('Heroes: ', allHeroes); })(); ``` -------------------------------- ### Install RxDB Backup Plugin Source: https://rxdb.info/backup.html?code=JD1&console=errors Import and add the RxDB Backup Plugin to your RxDB instance. This is a required setup step before using backup functionalities. ```javascript import { addRxPlugin } from 'rxdb'; import { RxDBBackupPlugin } from 'rxdb/plugins/backup'; addRxPlugin(RxDBBackupPlugin); ``` -------------------------------- ### Install RxDB and SQLite Adapter Source: https://rxdb.info/react-native-database.html Install RxDB and the `react-native-quick-sqlite` adapter for bare React Native projects. This setup is required before configuring the database. ```bash npm install rxdb rxjs react-native-quick-sqlite ``` -------------------------------- ### CouchDB Replication Setup Source: https://rxdb.info/articles/alternatives/alternatives/pouchdb-alternative.html Configure RxDB to replicate with a CouchDB-compatible endpoint. This example sets up live replication and specifies batch sizes for pull and push operations. ```javascript import { replicateCouchDB } from 'rxdb/plugins/replication-couchdb'; const replicationState = replicateCouchDB({ replicationIdentifier: 'my-couchdb-replication', collection: db.items, url: 'https://example.com/db/items', live: true, pull: { batchSize: 60 }, push: { batchSize: 60 } }); await replicationState.awaitInitialReplication(); replicationState.error$.subscribe(err => { console.error('Replication error:', err); }); ``` -------------------------------- ### Create RxDatabase with LocalStorage Source: https://rxdb.info/electron-database.html Installs dependencies, creates an RxDatabase using the LocalStorage RxStorage, adds collections, inserts a document, and performs a query. Use this for initial setup and testing in renderer processes. ```javascript import { createRxDatabase } from 'rxdb'; import { getRxStorageLocalstorage } from 'rxdb/plugins/storage-localstorage'; // create database const db = await createRxDatabase({ name: 'exampledb', storage: getRxStorageLocalstorage() }); // create collections const collections = await myRxDatabase.addCollections({ humans: { /* ... */ } }); // insert document await collections.humans.insert({id: 'foo', name: 'bar'}); // run a query const result = await collections.humans.find({ selector: { name: 'bar' } }).exec(); // observe a query await collections.humans.find({ selector: { name: 'bar' } }).$.subscribe(result => {/* ... */}); ``` -------------------------------- ### RxDB CRDT Plugin Installation and Setup Source: https://rxdb.info/crdt.html?code=CRDT2&console=errors Demonstrates how to install and configure the RxDB CRDT plugin. This includes adding the plugin, defining the schema with CRDT fields, and inserting a document. ```javascript // import the relevant parts from the CRDT plugin import { getCRDTSchemaPart, RxDBcrdtPlugin } from 'rxdb/plugins/crdt'; // add the CRDT plugin to RxDB import { addRxPlugin } from 'rxdb'; addRxPlugin(RxDBcrdtPlugin); // create a database import { createRxDatabase } from 'rxdb'; import { getRxStorageLocalstorage } from 'rxdb/plugins/storage-localstorage'; const myDatabase = await createRxDatabase({ name: 'heroesdb', storage: getRxStorageLocalstorage() }); // create a schema with the CRDT options const mySchema = { version: 0, primaryKey: 'id', type: 'object', properties: { id: { type: 'string', maxLength: 100 }, points: { type: 'number', maximum: 100, minimum: 0 }, crdts: getCRDTSchemaPart() // use this field to store the CRDT operations }, required: ['id', 'points'], crdt: { field: 'crdts' } } // add a collection await db.addCollections({ users: { schema: mySchema } }); // insert a document const myDocument = await db.users.insert({id: 'alice', points: 0}); // run a CRDT operation that increments the 'points' by one await myDocument.updateCRDT({ ifMatch: { $inc: { points: 1 } } }); ``` -------------------------------- ### RxDB Collection and Reactive Query Setup Source: https://rxdb.info/articles/alternatives/signaldb-alternative.html Sets up a new RxDB database with a 'tasks' collection and demonstrates a reactive query that emits changes. Ensure RxDB and the Dexie plugin are installed. ```javascript import { createRxDatabase, addRxPlugin } from 'rxdb'; import { getRxStorageDexie } from 'rxdb/plugins/storage-dexie'; const db = await createRxDatabase({ name: 'tasksdb', storage: getRxStorageDexie() }); await db.addCollections({ tasks: { schema: { version: 0, primaryKey: 'id', type: 'object', properties: { id: { type: 'string', maxLength: 40 }, title: { type: 'string' }, done: { type: 'boolean' }, updatedAt: { type: 'number' } }, required: ['id', 'title', 'done', 'updatedAt'] } } }); // Reactive query: emits whenever the result set changes, // across tabs and after replication updates. const openTasks$ = db.tasks .find({ selector: { done: false } }) .sort({ updatedAt: 'desc' }) .$ ; openTasks$.subscribe(tasks => { console.log('Open tasks:', tasks.length); }); await db.tasks.insert({ id: 't1', title: 'Write SignalDB comparison', done: false, updatedAt: Date.now() }); ``` -------------------------------- ### Install Dependencies Source: https://rxdb.info/contribution.html After cloning the repository, navigate to the project directory and install the necessary dependencies using npm. ```bash cd rxdb && npm install ``` -------------------------------- ### Install expo-file-system Source: https://rxdb.info/rx-storage-filesystem-expo.html Install the expo-file-system dependency using npx. ```bash npx expo install expo-file-system ``` -------------------------------- ### Initialize RxDB Database in React Source: https://rxdb.info/articles/react-database.html Basic setup for creating an RxDB database instance within a React application. Ensure RxDB and RxJS are installed as dependencies. ```javascript import { createRxDatabase } from 'rxdb'; import { getRxStorageLocalstorage } from 'rxdb/plugins/storage-localstorage'; const db = await createRxDatabase({ name: 'heroesdb', storage: getRxStorageLocalstorage(), password: 'myPassword', multiInstance: true, eventReduce: true, cleanupPolicy: {} }); ``` -------------------------------- ### Start FoundationDB Docker Container Source: https://rxdb.info/rx-storage-foundationdb.html Run this npm script to start the FoundationDB Docker container and configure the database. ```bash npm run foundationdb:start ``` -------------------------------- ### Install Appwrite SDK and RxDB Source: https://rxdb.info/replication-appwrite.html Install the necessary packages for Appwrite SDK and RxDB using npm. ```bash npm install appwrite rxdb ``` -------------------------------- ### Example Setup of Replication Source: https://rxdb.info/articles/zero-latency-local-first.html Configure RxDB replication to synchronize data between a local collection and a server. This includes defining handlers for pulling data from the server and pushing local changes, with options for live replication and retry intervals. ```typescript import { replicateRxCollection } from 'rxdb/plugins/replication'; async function syncLocalTasks(db) { replicateRxCollection({ collection: db.tasks, replicationIdentifier: 'sync-tasks', // Define how to pull server documents and push local documents pull: { handler: async (lastCheckpoint, batchSize) => { // logic to retrieve updated tasks from the server since lastCheckpoint }, }, push: { handler: async (docs) => { // logic to post local changes to the server }, }, live: true, // continuously replicate retryTime: 5000, // retry on errors or disconnections }); } ``` -------------------------------- ### Install RxDB, RxJS, and Supabase Client Source: https://rxdb.info/articles/alternatives/alternatives/supabase-alternative.html Install the necessary npm packages for RxDB, RxJS, and the Supabase JavaScript client. ```bash npm install rxdb rxjs @supabase/supabase-js ``` -------------------------------- ### Serve Documentation Locally Source: https://rxdb.info/contribution.html Install documentation dependencies and serve the documentation locally to preview changes. Access it at http://localhost:4000/. ```bash npm run docs:install && npm run docs:serve ``` -------------------------------- ### Initialize LocalStorage Storage Source: https://rxdb.info/quickstart.html Get the RxStorage instance for LocalStorage, suitable for simple browser setups and small datasets. ```javascript import { getRxStorageLocalstorage } from 'rxdb/plugins/storage-localstorage'; let storage = getRxStorageLocalstorage(); ``` -------------------------------- ### Basic Remote RxStorage Setup Source: https://rxdb.info/rx-storage-remote.html Demonstrates how to set up the Remote RxStorage on both the client and the remote instance. The client uses `getRxStorageRemote` to connect, while the remote instance uses `exposeRxStorageRemote` to expose its storage. ```javascript // on the client import { getRxStorageRemote } from 'rxdb/plugins/storage-remote'; const storage = getRxStorageRemote({ identifier: 'my-id', mode: 'storage', messageChannelCreator: () => Promise.resolve({ messages$: new Subject(), send(msg) { // send to remote storage } }) }); const myDb = await createRxDatabase({ storage }); // on the remote import { getRxStorageLocalstorage } from 'rxdb/plugins/storage-localstorage'; import { exposeRxStorageRemote } from 'rxdb/plugins/storage-remote'; exposeRxStorageRemote({ storage: getRxStorageLocalstorage(), messages$: new Subject(), send(msg){ // send to other side } }); ``` -------------------------------- ### Creating an RxDB Database and Collection Source: https://rxdb.info/articles/alternatives/alternatives/supabase-alternative.html This example demonstrates how to set up a local-first RxDB database with a 'posts' collection, including schema definition and offline query execution. This works immediately offline. ```javascript import { createRxDatabase } from 'rxdb/plugins/core'; import { getRxStorageIndexedDB } from 'rxdb/plugins/storage-indexeddb'; const db = await createRxDatabase({ name: 'myapp', storage: getRxStorageIndexedDB() }); await db.addCollections({ posts: { schema: { title: 'post schema', version: 0, primaryKey: 'id', type: 'object', properties: { id: { type: 'string', maxLength: 100 }, title: { type: 'string' }, body: { type: 'string' }, authorId: { type: 'string', maxLength: 100 }, published: { type: 'boolean' }, updatedAt: { type: 'number' } }, required: ['id', 'title', 'body', 'authorId', 'published', 'updatedAt'], indexes: ['updatedAt', 'authorId'] } } }); // This works offline. No network required. const posts = await db.posts.find({ selector: { published: true }, sort: [{ updatedAt: 'desc' }] }).exec(); ``` -------------------------------- ### Create RxDatabase with OPFS Storage Source: https://rxdb.info/articles/alternatives/alternatives/rethinkdb-alternative.html This example shows how to initialize an RxDB database using the Origin Private File System (OPFS) storage plugin for potentially better performance in browser environments. ```javascript import { getRxStorageOpfs } from 'rxdb/plugins/storage-opfs'; const db = await createRxDatabase({ name: 'myapp', storage: getRxStorageOpfs() // use OPFS for better browser performance }); ``` -------------------------------- ### Basic Horizon Application Example Source: https://rxdb.info/articles/alternatives/alternatives/horizon-alternative.html Demonstrates connecting to a Horizon backend, accessing collections, storing documents, and subscribing to real-time changes using RxJS Observables. ```javascript // Horizon: connect to the backend const horizon = Horizon(); // Get a reference to a collection (table in RethinkDB) const messages = horizon('messages'); // Store a document messages.store({ id: 'msg-1', text: 'Hello, Horizon!', createdAt: new Date() }); // Watch for realtime changes - returns an RxJS Observable messages.watch().subscribe(allMessages => { renderMessages(allMessages); }); // Fetch once (not live) messages.fetch().subscribe(allMessages => { console.log(allMessages); }); // Order and limit messages.order('createdAt', 'descending').limit(20).watch().subscribe(recent => { renderRecentMessages(recent); }); ``` -------------------------------- ### Basic CouchDB Replication Setup Source: https://rxdb.info/articles/alternatives/alternatives/couchdb-alternative.html Sets up live replication with a CouchDB instance, including batch sizes for pull and push operations. Use this for standard replication needs. ```javascript import { replicateCouchDB } from 'rxdb/plugins/replication-couchdb'; const replicationState = replicateCouchDB({ replicationIdentifier: 'my-couchdb-replication', collection: db.todos, url: 'http://example.com/db/todos', live: true, pull: { batchSize: 60 }, push: { batchSize: 60 } }); // Wait for the first sync to complete await replicationState.awaitInitialReplication(); // Monitor errors replicationState.error$.subscribe(err => { console.error('Replication error:', err); }); ``` -------------------------------- ### Create RxDatabase with Capacitor SQLite Source: https://rxdb.info/rx-storage-sqlite.html Use `getSQLiteBasicsCapacitor` to get the capacitor sqlite wrapper for RxDB. This example demonstrates creating a RxDatabase instance with the SQLite storage plugin for Capacitor. ```typescript import { createRxDatabase } from 'rxdb'; import { getRxStorageSQLite, getSQLiteBasicsCapacitor } from 'rxdb-premium/plugins/storage-sqlite'; /** * Import SQLite from the capacitor plugin. */ import { CapacitorSQLite, SQLiteConnection } from '@capacitor-community/sqlite'; import { Capacitor } from '@capacitor/core'; const sqlite = new SQLiteConnection(CapacitorSQLite); const myRxDatabase = await createRxDatabase({ name: 'exampledb', storage: getRxStorageSQLite({ /** * Different runtimes have different interfaces to SQLite. * For example in node.js we have a callback API, * while in capacitor sqlite we have Promises. * So we need a helper object that is capable of doing the basic * sqlite operations. */ sqliteBasics: getSQLiteBasicsCapacitor(sqlite, Capacitor) }) }); ``` -------------------------------- ### Create RxDatabase with LocalStorage Source: https://rxdb.info/rx-database.html?code=UT8&console=errors Demonstrates the basic creation of an RxDatabase using the LocalStorage RxStorage, suitable for browser environments. Includes optional parameters for password, multi-instance support, event reduction, and cleanup policy. ```javascript import { createRxDatabase } from 'rxdb/plugins/core'; import { getRxStorageLocalstorage } from 'rxdb/plugins/storage-localstorage'; const db = await createRxDatabase({ name: 'heroesdb', // <- name storage: getRxStorageLocalstorage(), // <- RxStorage /* Optional parameters: */ password: 'myPassword', // <- password (optional) multiInstance: true, // <- multiInstance (optional, default: true) eventReduce: true, // <- eventReduce (optional, default: false) cleanupPolicy: {} // <- custom cleanup policy (optional) }); ``` -------------------------------- ### Set Custom Push Initial Checkpoint Source: https://rxdb.info/replication.html?code=RC_OUTDATED&console=errors Configures the push replication to start pushing only documents that are newer than a specified checkpoint. This is achieved by setting the `push.initialCheckpoint` option during replication setup. ```javascript // store the latest checkpoint of a collection let lastLocalCheckpoint: any; myCollection.checkpoint$.subscribe(checkpoint => lastLocalCheckpoint = checkpoint) // start the replication but only push documents // that are newer than the lastLocalCheckpoint const replicationState = replicateRxCollection({ collection: myCollection, replicationIdentifier: 'my-custom-replication-with-init-checkpoint', /* ... */ push: { handler: /* ... */, initialCheckpoint: lastLocalCheckpoint } }); ``` -------------------------------- ### Encryption at Rest Setup Source: https://rxdb.info/articles/alternatives/alternatives/horizon-alternative.html RxDB's encryption plugin encrypts document fields before writing to local storage, decrypting them on read. This example uses Crypto-JS for encryption with IndexedDB. ```javascript import { wrappedKeyEncryptionCryptoJsStorage } from 'rxdb/plugins/encryption-crypto-js'; import { getRxStorageIndexedDB } from 'rxdb/plugins/storage-indexeddb'; const db = await createRxDatabase({ name: 'myapp', storage: wrappedKeyEncryptionCryptoJsStorage({ storage: getRxStorageIndexedDB() }), password: 'your-encryption-passphrase' }); const schema = { version: 0, primaryKey: 'id', type: 'object', properties: { id: { type: 'string', maxLength: 100 }, text: { type: 'string' }, sensitiveData: { type: 'string' } }, encrypted: ['sensitiveData'] // stored as ciphertext in IndexedDB }; ``` -------------------------------- ### RxDB CRDT Plugin Setup and Usage Source: https://rxdb.info/crdt.html?code=CRDT3&console=errors Demonstrates how to install and configure the RxDB CRDT plugin. This includes adding the plugin, defining a schema with CRDT support, and performing a CRDT operation. ```javascript // import the relevant parts from the CRDT plugin import { getCRDTSchemaPart, RxDBcrdtPlugin } from 'rxdb/plugins/crdt'; // add the CRDT plugin to RxDB import { addRxPlugin } from 'rxdb'; addRxPlugin(RxDBcrdtPlugin); // create a database import { createRxDatabase } from 'rxdb'; import { getRxStorageLocalstorage } from 'rxdb/plugins/storage-localstorage'; const myDatabase = await createRxDatabase({ name: 'heroesdb', storage: getRxStorageLocalstorage() }); // create a schema with the CRDT options const mySchema = { version: 0, primaryKey: 'id', type: 'object', properties: { id: { type: 'string', maxLength: 100 }, points: { type: 'number', maximum: 100, minimum: 0 }, crdts: getCRDTSchemaPart() // use this field to store the CRDT operations }, required: ['id', 'points'], crdt: { // CRDT options field: 'crdts' } } // add a collection await db.addCollections({ users: { schema: mySchema } }); // insert a document const myDocument = await db.users.insert({id: 'alice', points: 0}); // run a CRDT operation that increments the 'points' by one await myDocument.updateCRDT({ ifMatch: { $inc: { points: 1 } } }); ``` -------------------------------- ### RxDB TypeScript Example Source: https://rxdb.info/tutorials/typescript.html This snippet shows the complete setup and usage of RxDB with TypeScript, including database and collection creation, schema definition, ORM methods, hooks, data manipulation, and cleanup. ```typescript /** * create database and collections */ const myDatabase: MyDatabase = await createRxDatabase({ name: 'mydb', storage: getRxStorageLocalstorage() }); const heroSchema: RxJsonSchema = { title: 'human schema', description: 'describes a human being', version: 0, keyCompression: true, primaryKey: 'passportId', type: 'object', properties: { passportId: { type: 'string', maxLength: 100 }, firstName: { type: 'string' }, lastName: { type: 'string' }, age: { type: 'integer' } }, required: ['passportId', 'firstName', 'lastName'] }; const heroDocMethods: HeroDocMethods = { scream: function(this: HeroDocument, what: string) { return this.firstName + ' screams: ' + what.toUpperCase(); } }; const heroCollectionMethods: HeroCollectionMethods = { countAllDocuments: async function(this: HeroCollection) { const allDocs = await this.find().exec(); return allDocs.length; } }; await myDatabase.addCollections({ heroes: { schema: heroSchema, methods: heroDocMethods, statics: heroCollectionMethods } }); // add a postInsert-hook myDatabase.heroes.postInsert( function myPostInsertHook( this: HeroCollection, // own collection is bound to the scope docData: HeroDocType, // documents data doc: HeroDocument // RxDocument ) { console.log('insert to ' + this.name + '-collection: ' + doc.firstName); }, false // not async ); /** * use the database */ // insert a document const hero: HeroDocument = await myDatabase.heroes.insert({ passportId: 'myId', firstName: 'piotr', lastName: 'potter', age: 5 }); // access a property console.log(hero.firstName); // use a orm method hero.scream('AAH!'); // use a static orm method from the collection const amount: number = await myDatabase.heroes.countAllDocuments(); console.log(amount); /** * clean up */ myDatabase.close(); ``` -------------------------------- ### Configure a Live Database Backup Source: https://rxdb.info/backup.html Set up an ongoing backup that captures all changes made to the database in real-time. This is achieved by setting `live: true` in the backup options. The initial backup can still be awaited, but subsequent changes will be continuously written. ```javascript const backupOptions = { // set live: true to have an ongoing backup live: true, directory: '/my-backup-folder/', attachments: true } const backupState = myDatabase.backup(backupOptions); // you can still await the initial backup write, // but further changes will still be processed. await backupState.awaitInitialBackup(); ``` -------------------------------- ### Subscribe to a Single Document Field Change Source: https://rxdb.info/articles/alternatives/alternatives/meteor-alternative.html This example demonstrates how to subscribe to changes of a specific field ('text') within a single RxDB document. It first retrieves the document and then uses the `get$` method to observe field updates. ```javascript // Subscribe to a single document and watch one field const doc = await db.messages.findOne('msg-001').exec(); doc.get$('text').subscribe(newText => { console.log('Text changed to:', newText); }); ``` -------------------------------- ### RxDB Leader Election with LocalStorage Storage Source: https://rxdb.info/leader-election.html This example demonstrates how to set up a RxDB database with local storage and initiate data pulling only when the current tab becomes the leader. The pulling starts after the database instance successfully waits for leadership. ```typescript import { getRxStorageLocalstorage } from 'rxdb/plugins/storage-localstorage'; const db = await createRxDatabase({ name: 'weatherDB', storage: getRxStorageLocalstorage(), password: 'myPassword', multiInstance: true }); await db.addCollections({ temperature: { schema: mySchema } }); db.waitForLeadership() .then(() => { console.log('Long lives the king!'); // <- runs when db becomes leader setInterval(async () => { const temp = await fetch('https://example.com/api/temp/'); db.temperature.insert({ degrees: temp, time: new Date().getTime() }); }, 1000 * 10); }); ``` -------------------------------- ### Create RxDB Database with DenoKV Storage Source: https://rxdb.info/rx-storage-denokv.html Demonstrates how to initialize an RxDB database using the DenoKV RxStorage plugin. Configure consistency level, KV path, and batch size for optimal performance. ```typescript import { createRxDatabase } from 'rxdb'; import { getRxStorageDenoKV } from 'rxdb/plugins/storage-denokv'; const myRxDatabase = await createRxDatabase({ name: 'exampledb', storage: getRxStorageDenoKV({ /** * Consistency level, either 'strong' or 'eventual' * (Optional) default='strong' */ consistencyLevel: 'strong', /** * Path which is used in the first argument of Deno.openKv(settings.openKvPath) * (Optional) default='' */ openKvPath: './foobar', /** * Some operations have to run in batches, * you can test different batch sizes to improve performance. * (Optional) default=100 */ batchSize: 100 }) }); ``` -------------------------------- ### RxDB Backend-Agnostic Replication Setup Source: https://rxdb.info/articles/alternatives/alternatives/minimongo-alternative.html Implement custom replication logic using RxDB's pull/push interface. This example shows how to set up live replication with a custom HTTP endpoint, including error handling and automatic retries. ```typescript import { replicateRxCollection } from 'rxdb/plugins/replication'; const replicationState = await replicateRxCollection({ collection: db.posts, replicationIdentifier: 'posts-replication-v1', pull: { handler: async (checkpoint, batchSize) => { const response = await fetch( `/api/posts/pull?since=${checkpoint?.updatedAt ?? 0}` + `&limit=${batchSize}` ); return response.json(); // { documents: [...], checkpoint: {...} } } }, push: { handler: async (rows) => { const response = await fetch('/api/posts/push', { method: 'POST', body: JSON.stringify(rows), headers: { 'Content-Type': 'application/json' } }); return response.json(); // return conflicting documents if any } }, live: true, retryTime: 5000 }); replicationState.error$.subscribe(err => { console.error('Replication error:', err); }); ``` -------------------------------- ### Start P2P Replication with WebRTC Source: https://rxdb.info/replication-webrtc.html?code=RC7&console=errors Initiates P2P replication for a specific RxDB collection using WebRTC. Requires a topic for peer discovery and a connection handler, typically `getConnectionHandlerSimplePeer` for basic setups. Ensure correct signaling server URLs and necessary Node.js polyfills if applicable. ```javascript const replicationPool = await replicateWebRTC( { // Start the replication for a single collection collection: db.todos, // The topic is like a 'room-name'. All clients with the same topic // will replicate with each other. In most cases you want to use // a different topic string per user. Also you should prefix the topic with // a unique identifier for your app, to ensure // you do not let your users connect // with other apps that also use the RxDB P2P Replication. topic: 'my-users-pool', /** * You need a collection handler to be able to create WebRTC connections. * Here we use the simple peer handler which * uses the 'simple-peer' npm library. * To learn how to create a custom connection handler, read the source code, * it is pretty simple. */ connectionHandlerCreator: getConnectionHandlerSimplePeer({ // Set the signaling server url. // You can use the server provided by RxDB for tryouts, // but in production you should use your own server instead. signalingServerUrl: 'wss://signaling.rxdb.info/', // only in Node.js, we need the wrtc library // because Node.js does not have WebRTC. // Wrap with createSimplePeerWrtc(). wrtc: createSimplePeerWrtc( require('node-datachannel/polyfill') ), // only in Node.js, we need the WebSocket library // because Node.js does not contain the WebSocket API. webSocketConstructor: require('ws').WebSocket }), pull: {}, push: {} } ); ``` -------------------------------- ### Configure a Live Database Backup Source: https://rxdb.info/backup.html?code=JD1&console=errors Set up an ongoing backup that captures all changes made to the database after the initial write. The backup process continues to monitor and write new data. ```javascript const backupOptions = { // set live: true to have an ongoing backup live: true, directory: '/my-backup-folder/', attachments: true } const backupState = myDatabase.backup(backupOptions); // you can still await the initial backup write, // but further changes will still be processed. await backupState.awaitInitialBackup(); ``` -------------------------------- ### pause() and start() Source: https://rxdb.info/replication.html?code=RC_FORBIDDEN&console=errors Pauses a currently running replication. The replication can be resumed later using the `start()` method. The `start()` method is used to resume a paused replication. ```APIDOC ## pause() and start() ### Description Pauses a running replication. The replication can later be resumed with `RxReplicationState.start()`. ### Methods `await myRxReplicationState.pause();` `await myRxReplicationState.start(); // restart` ``` -------------------------------- ### Run FoundationDB Server with Docker Source: https://rxdb.info/rx-storage-foundationdb.html Set up a FoundationDB server instance using Docker for local development and CI. This includes pulling the image, starting the container, and copying the cluster file. ```bash # Pull the Docker image docker pull foundationdb/foundationdb:7.3.59 # Start the container with host networking docker run -d \ --name rxdb-foundationdb \ --network host \ -e FDB_NETWORKING_MODE=host \ foundationdb/foundationdb:7.3.59 # Copy the cluster file from the container sudo mkdir -p /etc/foundationdb docker cp rxdb-foundationdb:/var/fdb/fdb.cluster /etc/foundationdb/fdb.cluster ``` -------------------------------- ### Initialize RxDB with Localstorage Storage Source: https://rxdb.info/articles/vue-database.html Set up an RxDB database instance using the Localstorage storage plugin. This example defines a 'heroesdb' database with a 'hero' collection, including schema definition for id, name, and healthpoints. ```javascript // db.js import { createRxDatabase } from 'rxdb'; import { getRxStorageLocalstorage } from 'rxdb/plugins/storage-localstorage'; export async function initDatabase() { const db = await createRxDatabase({ name: 'heroesdb', storage: getRxStorageLocalstorage(), password: 'myPassword', // optional encryption password multiInstance: true, // multi-tab support eventReduce: true // optimize event handling }); await db.addCollections({ hero: { schema: { title: 'hero schema', version: 0, primaryKey: 'id', type: 'object', properties: { id: { type: 'string', maxLength: 100 }, name: { type: 'string' }, healthpoints: { type: 'number' } } } } }); return db; } ``` -------------------------------- ### Install react-native-sqlite-2 Source: https://rxdb.info/adapters.html Install the necessary packages for the react-native-sqlite adapter. ```bash npm install pouchdb-adapter-react-native-sqlite react-native-sqlite-2 ``` -------------------------------- ### Create RxDatabase with LocalStorage Source: https://rxdb.info/rx-database.html?code=DB9&console=errors Demonstrates the creation of an RxDatabase instance using the LocalStorage RxStorage, suitable for browser environments. Includes essential parameters like name and storage implementation. ```javascript import { createRxDatabase } from 'rxdb/plugins/core'; import { getRxStorageLocalstorage } from 'rxdb/plugins/storage-localstorage'; const db = await createRxDatabase({ name: 'heroesdb', // <- name storage: getRxStorageLocalstorage(), // <- RxStorage /* Optional parameters: */ password: 'myPassword', // <- password (optional) multiInstance: true, // <- multiInstance (optional, default: true) eventReduce: true, // <- eventReduce (optional, default: false) cleanupPolicy: {} }); ```