### Start Appwrite Instance Source: https://rxdb.info/replication-appwrite Use docker-compose up to start the Appwrite instance after installation or if it was previously stopped. ```bash docker-compose up ``` -------------------------------- ### RxDB CRDT Plugin Installation and Setup Source: https://rxdb.info/crdt Demonstrates how to install and configure the RxDB CRDT plugin, including schema setup and initial document insertion. ```typescript // 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 } } }); ``` -------------------------------- ### Install Dependencies Source: https://rxdb.info/contribute Navigate to the RxDB directory and install the project dependencies using npm. ```bash cd rxdb && npm install ``` -------------------------------- ### Query Examples Source: https://rxdb.info/rx-query Examples demonstrating how to write RxDB queries. ```APIDOC ## Query Examples Here some examples to learn quickly how to write queries without reading the docs. - [Pouch-find-docs](https://github.com/pouchdb/pouchdb/blob/master/packages/node_modules/pouchdb-find/README.md) - learn how to use mango-queries - [mquery-docs](https://github.com/aheckmann/mquery/blob/master/README.md) - learn how to use chained-queries ```js // directly pass search-object myCollection.find({ selector: { name: { $eq: 'foo' } } }) .exec().then(documents => console.dir(documents)); /* * find by using sql equivalent '%like%' syntax * This example will e.g. match 'foo' but also 'fifoo' or 'foofa' or 'fifoofa' * Notice that in RxDB queries, a regex is * represented as a $regex string with the * $options parameter for flags. * Using a RegExp instance is not allowed * because they are not JSON.stringify()-able * and also RegExp instances are mutable which * could cause undefined behavior when the * RegExp is mutated * after the query was parsed. */ myCollection.find({ selector: { name: { $regex: '.*foo.*' } } }) .exec().then(documents => console.dir(documents)); // find using a composite statement eg: $or // This example checks where name is either foo // or if name is not existent on the document myCollection.find({ selector: { $or: [ { name: { $eq: 'foo' } }, { name: { $exists: false } }] } }) .exec().then(documents => console.dir(documents)); // do a case insensitive search // This example will match 'foo' or 'FOO' or 'FoO' etc... myCollection.find({ selector: { name: { $regex: '^foo$', $options: 'i' } } }) .exec().then(documents => console.dir(documents)); // chained queries myCollection.find().where('name').eq('foo') .exec().then(documents => console.dir(documents)); ``` :::note RxDB will always append the primary key to the sort parameters For several performance optimizations, like the [EventReduce algorithm](https://github.com/pubkey/event-reduce), RxDB expects all queries to return a deterministic sort order that does not depend on the insert order of the documents. To ensure a deterministic ordering, RxDB will always append the primary key as last sort parameter to all queries and to all indexes. This works in contrast to most other databases where a query without sorting would return the documents in the order in which they had been inserted to the database. ::: ``` -------------------------------- ### Create RxServer with Express Adapter Source: https://rxdb.info/rx-server Installs the rxdb-server package and creates an RxServer instance using the Express adapter. Ensure Express is installed in the correct version. The server must be started explicitly with `myServer.start()` after adding endpoints. ```typescript import { createRxServer } from 'rxdb-server/plugins/server'; /** * We use the express adapter which is the one that comes with RxDB core * Make sure you have express installed in the correct version! * @see https://github.com/pubkey/rxdb-server/blob/master/package.json */ import { RxServerAdapterExpress } from 'rxdb-server/plugins/adapter-express'; const myServer = await createRxServer({ database: myRxDatabase, adapter: RxServerAdapterExpress, port: 443 }); // add endpoints here (see below) // after adding the endpoints, start the server await myServer.start(); ``` -------------------------------- ### Install RxDB and RxJS Source: https://rxdb.info/articles/react-indexeddb Install RxDB and RxJS using npm to begin using RxDB in your React project. This is the initial setup step for integrating RxDB. ```bash npm install rxdb rxjs --save ``` -------------------------------- ### RxDB Setup with Local Storage in TypeScript Source: https://rxdb.info/articles/reactjs-storage Initializes an RxDB database using the local storage adapter. This is a common starting point for offline-first applications. Ensure RxDB and the storage plugin are installed. ```typescript 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 expo-file-system Source: https://rxdb.info/rx-storage-filesystem-expo Install the expo-file-system dependency for the RxStorage plugin. ```bash npx expo install expo-file-system ``` -------------------------------- ### Install Appwrite SDK and RxDB Source: https://rxdb.info/replication-appwrite Install the necessary packages for Appwrite and RxDB using npm. ```bash npm install appwrite rxdb ``` -------------------------------- ### Starting the Websocket Server Source: https://rxdb.info/replication-websocket This snippet demonstrates how to initialize a RxDB database and then start a WebSocket server for replication. It also shows how to close the server. ```APIDOC ## startWebsocketServer ### Description Starts a WebSocket server from a RxDB database instance. ### Method `startWebsocketServer(options)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **database** (RxDatabase) - Required - The RxDB database instance to replicate. - **port** (number) - Required - The port number for the WebSocket server. - **path** (string) - Required - The path for the WebSocket endpoint. ### Request Example ```typescript import { createRxDatabase } from 'rxdb'; import { startWebsocketServer } from 'rxdb/plugins/replication-websocket'; const myDatabase = await createRxDatabase({/* ... */}); const serverState = await startWebsocketServer({ database: myDatabase, port: 1337, path: '/socket' }); // To stop the server: await serverState.close(); ``` ### Response #### Success Response (200) Returns an object with a `close` method to stop the server. #### Response Example ```json { "close": "() => Promise" } ``` ``` -------------------------------- ### Start MongoDB Server (Shell) Source: https://rxdb.info/replication-mongodb Start a local MongoDB server with replica set initialization for changestream compatibility. ```bash mongod --replSet rs0 --bind_ip_all ``` -------------------------------- ### Install RxDB and Supabase JS Client Source: https://rxdb.info/replication-supabase Install the necessary packages for RxDB and Supabase integration. This is the first step to setting up synchronization. ```bash npm install rxdb @supabase/supabase-js ``` -------------------------------- ### Remove Unused Dependencies Prompt Source: https://rxdb.info/articles/generic-prompts Guides an agent to find and remove unused dependencies to reduce install times, token usage, and supply-chain attack risks. It emphasizes verifying that dependencies are truly unused before removal and creating a pull request. ```txt Run the installation and find dependencies that are not used anymore. Ensure that these are really not used, not on the core and not in the tests. Remove these unused dependencies and make a pull request. ``` -------------------------------- ### Install Dexie Cloud Addon Source: https://rxdb.info/rx-storage-dexie Install the dexie-cloud-addon package to enable synchronization with Dexie Cloud. ```bash npm install dexie-cloud-addon ``` -------------------------------- ### Install RxDB and React Source: https://rxdb.info/react Install RxDB and React dependencies using npm. ```bash npm install rxdb react react-dom ``` -------------------------------- ### Basic Remote RxStorage Client and Server Setup Source: https://rxdb.info/rx-storage-remote Client-side setup for Remote RxStorage using a custom message channel creator. Server-side setup uses `exposeRxStorageRemote` to expose a local storage implementation over the same message channel. ```typescript // 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 } }); ``` -------------------------------- ### Install RxDB Source: https://rxdb.info/articles/firebase-realtime-database-alternative Install RxDB and RxJS using npm. This command is the first step to integrating RxDB into your project. ```bash npm install rxdb rxjs ``` -------------------------------- ### Starting Replication with Pure Function Source: https://rxdb.info/releases/14.0.0 Shows the new way to start replication by importing and calling a pure function, improving tree-shaking and typings. ```typescript import { replicateCouchDB } from 'rxdb/plugins/replication-couchdb'; const replicationState = replicateCouchDB({ /* ... */ }); ``` -------------------------------- ### Get RxStorageSQLiteTrial (Node.js) Source: https://rxdb.info/quickstart Import and get the SQLite Trial RxStorage for Node.js, suitable for quick experimentation with SQLite. ```typescript import { getRxStorageSQLiteTrial, getSQLiteBasicsNodeNative } from 'rxdb/plugins/storage-sqlite'; import { DatabaseSync } from 'node:sqlite'; const storage = getRxStorageSQLiteTrial({ sqliteBasics: getSQLiteBasicsNodeNative(DatabaseSync) }); ``` -------------------------------- ### Install RxDB and CryptoJS Encryption Plugin Source: https://rxdb.info/articles/react-native-encryption Install RxDB and the crypto-js package for basic encryption. This is the first step before setting up an encrypted database. ```bash npm install rxdb npm install crypto-js ``` -------------------------------- ### Run Appwrite Installation Script Source: https://rxdb.info/replication-appwrite Execute the Appwrite installation script using Docker. This command mounts the current directory to persist configuration files. ```bash docker run -it --rm \ --volume /var/run/docker.sock:/var/run/docker.sock \ --volume $(pwd)/appwrite:/usr/src/code/appwrite:rw \ --entrypoint="install" \ appwrite/appwrite:1.6.1 ``` -------------------------------- ### Install WebMCP Polyfill Source: https://rxdb.info/webmcp Install the WebMCP polyfill package to enable navigator.modelContext in browsers without native support. This should be done before registering any WebMCP tools. ```bash npm install @mcp-b/global ``` -------------------------------- ### Query Examples Source: https://rxdb.info/llms-api.txt Provides various examples of constructing RxDB queries using different operators and methods, including direct selector objects and chained queries. ```APIDOC ## Query Examples Here some examples to learn quickly how to write queries without reading the docs. - [Pouch-find-docs](https://github.com/pouchdb/pouchdb/blob/master/packages/node_modules/pouchdb-find/README.md) - learn how to use mango-queries - [mquery-docs](https://github.com/aheckmann/mquery/blob/master/README.md) - learn how to use chained-queries ```js // directly pass search-object myCollection.find({ selector: { name: { $eq: 'foo' } } }) .exec().then(documents => console.dir(documents)); /* * find by using sql equivalent '%like%' syntax * This example will e.g. match 'foo' but also 'fifoo' or 'foofa' or 'fifoofa' * Notice that in RxDB queries, a regex is * represented as a $regex string with the * $options parameter for flags. * Using a RegExp instance is not allowed * because they are not JSON.stringify()-able * and also RegExp instances are mutable which * could cause undefined behavior when the * RegExp is mutated * after the query was parsed. */ myCollection.find({ selector: { name: { $regex: '.*foo.*' } } }) .exec().then(documents => console.dir(documents)); // find using a composite statement eg: $or // This example checks where name is either foo // or if name is not existent on the document myCollection.find({ selector: { $or: [ { name: { $eq: 'foo' } }, { name: { $exists: false } }] } }) .exec().then(documents => console.dir(documents)); // do a case insensitive search // This example will match 'foo' or 'FOO' or 'FoO' etc... myCollection.find({ selector: { name: { $regex: '^foo$', $options: 'i' } } }) .exec().then(documents => console.dir(documents)); // chained queries myCollection.find().where('name').eq('foo') .exec().then(documents => console.dir(documents)); ``` :::note RxDB will always append the primary key to the sort parameters For several performance optimizations, like the [EventReduce algorithm](https://github.com/pubkey/event-reduce), RxDB expects all queries to return a deterministic sort order that does not depend on the insert order of the documents. To ensure a deterministic ordering, RxDB will always append the primary key as last sort parameter to all queries and to all indexes. This works in contrast to most other databases where a query without sorting would return the documents in the order in which they had been inserted to the database. ::: ``` -------------------------------- ### Get RxStorageSQLite (Premium Node.js) Source: https://rxdb.info/quickstart Import and get the premium SQLite RxStorage for Node.js, providing fast, durable disk storage. Requires a sqlite3-compatible library. ```typescript import { getRxStorageSQLite, getSQLiteBasicsNode } from 'rxdb-premium/plugins/storage-sqlite'; // Provide the sqliteBasics adapter for your runtime, e.g. Node.js, React Native, etc. // For example in Node.js you would derive // sqliteBasics from a sqlite3-compatible library: import sqlite3 from 'sqlite3'; const storage = getRxStorageSQLite({ sqliteBasics: getSQLiteBasicsNode(sqlite3) }); ``` -------------------------------- ### Serve Documentation Locally Source: https://rxdb.info/contribute Install and serve the RxDB documentation locally to preview changes or read the docs offline. ```bash npm run docs:install && npm run docs:serve ``` -------------------------------- ### Get RxStorageLocalstorage Source: https://rxdb.info/quickstart Import and get the LocalStorage RxStorage plugin for simple browser setups. ```typescript import { getRxStorageLocalstorage } from 'rxdb/plugins/storage-localstorage'; let storage = getRxStorageLocalstorage(); ``` -------------------------------- ### Initialize RxDB with Localstorage Source: https://rxdb.info/articles/vue-database Set up an RxDB instance using the Localstorage storage engine. This example configures the database with a name, storage, password, multi-instance support, and event optimization, and defines a 'hero' collection with a specific schema. ```typescript // 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; } ``` -------------------------------- ### RxDB Leader Election Example Source: https://rxdb.info/leader-election This example demonstrates how to use RxDB's leader election to start data pulling only when the tab becomes the leader. It saves fetched temperature data to a collection. ```javascript 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); }); ``` -------------------------------- ### Replication and Migration Setup for Memory Synced Storage Source: https://rxdb.info/rx-storage-memory-synced Use this pattern when you need to perform replication and migration with memory-synced storage. Create a parent database with the same name and collections as the memory-synced database, and ensure the parent database is created before the memory-synced one to allow migration to run first. Replication is then set up on the parent collection. ```javascript const parentStorage = getRxStorageIndexedDB(); const memorySyncedStorage = getMemorySyncedRxStorage({ storage: parentStorage, keepIndexesOnParent: true }); const databaseName = 'mydata'; /** * Create a parent database with the same name+collections * and use it for replication and migration. * The parent database must be created BEFORE the memory-synced database * to ensure migration has already been run. */ const parentDatabase = await createRxDatabase({ name: databaseName, storage: parentStorage }); await parentDatabase.addCollections({ /* ... */ }); replicateRxCollection({ collection: parentDatabase.myCollection, /* ... */ }); /** * Create an equal memory-synced database with the same name+collections * and use it for writes and queries. */ const memoryDatabase = await createRxDatabase({ name: databaseName, storage: memorySyncedStorage }); await memoryDatabase.addCollections({ /* ... */ }); ``` -------------------------------- ### Setup Remote RxStorage Client and Server Source: https://rxdb.info/llms-storages.txt Demonstrates how to initialize a Remote RxStorage client on one side and expose it on the other. Requires a custom message channel implementation. ```typescript 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 }); ``` ```typescript 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 } }); ``` -------------------------------- ### Expose RxStorage and Setup Replication in SharedWorker Source: https://rxdb.info/llms-storages.txt Inside the SharedWorker, expose the RxStorage using `exposeWorkerRxStorage` and then create a normal RxDatabase instance to set up collections and start replication. This approach centralizes database operations and replication within the worker for better performance. ```typescript // shared-worker.ts import { exposeWorkerRxStorage } from 'rxdb-premium/plugins/storage-worker'; import { getRxStorageIndexedDB } from 'rxdb-premium/plugins/storage-indexeddb'; import { createRxDatabase, addRxPlugin } from 'rxdb'; import { RxDBReplicationGraphQLPlugin } from 'rxdb/plugins/replication-graphql'; addRxPlugin(RxDBReplicationGraphQLPlugin); const baseStorage = getRxStorageIndexedDB(); // first expose the RxStorage to the outside exposeWorkerRxStorage({ storage: baseStorage }); /** * Then create a normal RxDatabase and RxCollections * and start the replication. */ const database = await createRxDatabase({ name: 'mydatabase', storage: baseStorage }); await db.addCollections({ humans: {/* ... */} }); const replicationState = db.humans.syncGraphQL({/* ... */}); ``` -------------------------------- ### Install RxDB with Expo SQLite Source: https://rxdb.info/react-native-database Install RxDB and the expo-sqlite adapter for Expo projects. Ensure you also install the 'expo-sqlite' module itself. ```bash npx expo install expo-sqlite npm install rxdb rxjs ``` -------------------------------- ### Install Expo Modules for Bare React Native Source: https://rxdb.info/rx-storage-filesystem-expo Install Expo modules and the file system package in a bare React Native project. Run `npx pod-install` on iOS after installation. ```bash npx install-expo-modules@latest npx expo install expo-file-system ``` -------------------------------- ### Create RxDatabase with wa-sqlite in Browser Source: https://rxdb.info/llms-storages.txt Set up an RxDatabase in the browser using WebAssembly via the 'wa-sqlite' package. Note that this can be slower than other browser storages. ```typescript import { createRxDatabase } from 'rxdb'; import { getRxStorageSQLite, getSQLiteBasicsWasm } from 'rxdb-premium/plugins/storage-sqlite'; /** * In the Browser, we use the SQLite database * from the 'wa-sqlite' npm module. This contains the SQLite library * compiled to Webassembly * @link https://www.npmjs.com/package/wa-sqlite */ import SQLiteESMFactory from 'wa-sqlite/dist/wa-sqlite-async.mjs'; import SQLite from 'wa-sqlite'; const sqliteModule = await SQLiteESMFactory(); const sqlite3 = SQLite.Factory(module); const myRxDatabase = await createRxDatabase({ name: 'exampledb', storage: getRxStorageSQLite({ sqliteBasics: getSQLiteBasicsWasm(sqlite3) }) }); ``` -------------------------------- ### Install expo-opfs Source: https://rxdb.info/rx-storage-filesystem-expo Install the expo-opfs peer dependency required by the RxStorage plugin. ```bash npx expo install expo-opfs ``` -------------------------------- ### Create an RxDatabase instance Source: https://rxdb.info/llms-api.txt Use createRxDatabase() to initialize an RxDatabase. Specify the database name and the RxStorage implementation. Optional parameters include password, multiInstance, eventReduce, and cleanupPolicy. ```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) }); ``` -------------------------------- ### Install Firebase Package Source: https://rxdb.info/replication-firestore Install the necessary Firebase package using npm. ```bash npm install firebase ``` -------------------------------- ### Run FoundationDB Server with Docker Source: https://rxdb.info/rx-storage-foundationdb Use these commands to pull the FoundationDB Docker image, start a container, copy the cluster file, and configure the database. This is recommended for local development and CI. ```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 # Configure the database fdbcli --exec "configure new single memory" --timeout 30 ``` ```bash npm run foundationdb:start # Starts the Docker container and configures the database npm run foundationdb:stop # Stops and removes the Docker container ``` -------------------------------- ### Create RxState Instance with RxDB Source: https://rxdb.info/rx-state Import RxDBStatePlugin, add it to RxDB, and then create a RxState instance on a RxDatabase. Multiple calls to addState with the same namespace are de-duplicated. ```javascript import { createRxDatabase, addRxPlugin } from 'rxdb'; import { getRxStorageLocalstorage } from 'rxdb/plugins/storage-localstorage'; // first add the RxState plugin to RxDB import { RxDBStatePlugin } from 'rxdb/plugins/state'; addRxPlugin(RxDBStatePlugin); const database = await createRxDatabase({ name: 'heroesdb', storage: getRxStorageLocalstorage(), }); // create a state instance const myState = await database.addState(); // you can also create states with a given namespace const myChildState = await database.addState('myNamepsace'); ``` -------------------------------- ### Install RxDB via npm Source: https://rxdb.info/install Installs the latest release of RxDB and its dependencies, saving them to package.json. ```bash npm i rxdb --save ``` -------------------------------- ### Create RxDatabase with LocalStorage RxStorage Source: https://rxdb.info/electron-database Demonstrates how to initialize an RxDatabase using the LocalStorage RxStorage plugin. This is suitable for renderer processes during development. ```typescript 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 => {/* ... */}); ``` -------------------------------- ### Create RxDatabase with LocalStorage or MongoDB RxStorage Source: https://rxdb.info/llms-api.txt Demonstrates creating an RxDatabase instance using either the LocalStorage RxStorage for browser environments or the MongoDB RxStorage for Node.js. Ensure the correct RxStorage plugin is imported based on your runtime environment. ```javascript import { getRxStorageLocalstorage } from 'rxdb/plugins/storage-localstorage'; const db = await createRxDatabase({ name: 'mydatabase', storage: getRxStorageLocalstorage() }); ``` ```javascript import { getRxStorageMongoDB } from 'rxdb/plugins/storage-mongodb'; const dbMongo = await createRxDatabase({ name: 'mydatabase', storage: getRxStorageMongoDB({ connection: 'mongodb://localhost:27017,localhost:27018,localhost:27019' }) }); ``` -------------------------------- ### Install RxDB with npm Source: https://rxdb.info/articles/angular-database Install the RxDB package as a dependency in your Angular project using npm. ```bash npm install rxdb --save ``` -------------------------------- ### Setup Local RxDB Database and Collections Source: https://rxdb.info/articles/zero-latency-local-first Initializes a local RxDB database using localstorage and defines a 'tasks' collection with its schema. Includes a reactive query to observe changes. ```typescript import { createRxDatabase } from 'rxdb/plugins/core'; import { getRxStorageLocalstorage } from 'rxdb/plugins/storage-localstorage'; async function initZeroLocalDB() { // Create a local RxDB instance using localstorage-based storage const db = await createRxDatabase({ name: 'myZeroLocalDB', storage: getRxStorageLocalstorage(), // optional: password for encryption if needed }); // Define one or more collections await db.addCollections({ tasks: { schema: { title: 'task schema', version: 0, type: 'object', primaryKey: 'id', properties: { id: { type: 'string', maxLength: 100 }, title: { type: 'string' }, done: { type: 'boolean' } } } } }); // Reactive query - automatically updates on local or remote changes db.tasks .find() .$ // returns an RxJS Observable .subscribe(allTasks => { console.log('All tasks updated:', allTasks); }); return db; } ``` -------------------------------- ### Get RxStorageDexie Source: https://rxdb.info/quickstart Import and get the Dexie.js RxStorage plugin, a reliable default for browser apps. ```typescript import { getRxStorageDexie } from 'rxdb/plugins/storage-dexie'; let storage = getRxStorageDexie(); ``` -------------------------------- ### Install RxJS Peer Dependency Source: https://rxdb.info/install Installs the RxJS peer dependency, which is required by RxDB if not already present. ```bash npm i rxjs --save ``` -------------------------------- ### Start MongoDB Server (Docker) Source: https://rxdb.info/replication-mongodb Run a MongoDB Docker container configured for replica set usage, suitable for local development. ```bash docker run -p 27017:27017 -p 27018:27018 -p 27019:27019 --rm --name rxdb-mongodb mongo:8.0.4 mongod --replSet rs0 --bind_ip_all ``` -------------------------------- ### Get RxStorageIndexedDB (Premium) Source: https://rxdb.info/quickstart Import and get the premium IndexedDB RxStorage plugin for high-performance browser storage. ```typescript import { getRxStorageIndexedDB } from 'rxdb-premium/plugins/storage-indexeddb'; let storage = getRxStorageIndexedDB(); ``` -------------------------------- ### Setup Express Server with MongoDB Source: https://rxdb.info/replication-http Initializes an Express server with a MongoDB connection to handle replication requests. Ensure MongoDB is running and accessible. ```typescript import { MongoClient } from 'mongodb'; import express from 'express'; const mongoClient = new MongoClient('mongodb://localhost:27017/'); const mongoConnection = await mongoClient.connect(); const mongoDatabase = mongoConnection.db('myDatabase'); const mongoCollection = await mongoDatabase.collection('myDocs'); const app = express(); app.use(express.json()); /* ... add routes from below */ app.listen(80, () => { console.log(`Example app listening on port 80`) }); ``` -------------------------------- ### Check Docker Compose Version Source: https://rxdb.info/replication-appwrite Verify that Docker Compose is installed and check its version before proceeding with Appwrite installation. ```bash docker-compose -v ``` -------------------------------- ### Install RxDB and MongoDB Dependencies Source: https://rxdb.info/replication-mongodb Install the necessary RxDB libraries and the MongoDB node.js driver for your JavaScript project. ```bash npm install rxdb rxdb-server mongodb --save ``` -------------------------------- ### RxDatabase with Different RxStorages Source: https://rxdb.info/rx-database Demonstrates creating RxDatabase instances with different RxStorage implementations, such as LocalStorage for browsers and MongoDB for Node.js. Ensure the appropriate storage plugin is imported. ```javascript // use the LocalStorage that stores data in the browser. import { getRxStorageLocalstorage } from 'rxdb/plugins/storage-localstorage'; const db = await createRxDatabase({ name: 'mydatabase', storage: getRxStorageLocalstorage() }); // ...or use the MongoDB RxStorage in Node.js. import { getRxStorageMongoDB } from 'rxdb/plugins/storage-mongodb'; const dbMongo = await createRxDatabase({ name: 'mydatabase', storage: getRxStorageMongoDB({ connection: 'mongodb://localhost:27017,localhost:27018,localhost:27019' }) }); ``` -------------------------------- ### Install Babel Polyfills Source: https://rxdb.info/install Installs the @babel/polyfill package to support older browsers by providing necessary ES8+ features. ```bash npm i @babel/polyfill --save ``` -------------------------------- ### Initialize Premium SQLite Storage (Node.js) Source: https://rxdb.info/llms-api.txt Set up the premium SQLite storage for environments like Node.js, React Native, or Electron. Requires a compatible sqlite3 library. ```typescript import { getRxStorageSQLite, getSQLiteBasicsNode } from 'rxdb-premium/plugins/storage-sqlite'; import sqlite3 from 'sqlite3'; const storage = getRxStorageSQLite({ sqliteBasics: getSQLiteBasicsNode(sqlite3) }); ``` -------------------------------- ### Create RxDatabase using Pre-built Worker Source: https://rxdb.info/rx-storage-worker This example shows how to use a pre-built worker file provided by RxDB Premium. Ensure the worker file is copied from `node_modules/rxdb-premium/dist/workers` to a location accessible by your webserver. ```typescript import { createRxDatabase } from 'rxdb'; import { getRxStorageWorker } from 'rxdb-premium/plugins/storage-worker'; const database = await createRxDatabase({ name: 'mydatabase', storage: getRxStorageWorker( { /** * Path to where the copied file from node_modules/rxdb/dist/workers * is reachable from the webserver. */ workerInput: '/indexeddb.worker.js' } ) }); ``` -------------------------------- ### Install MongoDB Driver Source: https://rxdb.info/rx-storage-mongodb Install the official MongoDB Node.js driver using npm. This is a prerequisite for using the MongoDB RxStorage. ```bash npm install mongodb --save ```