### Quick Setup: Create RxDB Database and Collection Source: https://github.com/pubkey/rxdb/blob/master/docs-src/docs/articles/offline-database.md This example demonstrates how to initialize an RxDB database using the local storage plugin, add a 'tasks' collection with a defined schema, and subscribe to real-time changes for undone tasks. It's a starting point for building offline-first applications. ```typescript import { createRxDatabase } from 'rxdb/plugins/core'; import { getRxStorageLocalstorage } from 'rxdb/plugins/storage-localstorage'; async function initDB() { // Create a local offline database const db = await createRxDatabase({ name: 'myOfflineDB', storage: getRxStorageLocalstorage() }); // Add collections await db.addCollections({ tasks: { schema: { title: 'tasks schema', version: 0, type: 'object', primaryKey: 'id', properties: { id: { type: 'string', maxLength: 100 }, title: { type: 'string' }, done: { type: 'boolean' } } } } }); // Observe changes in real time db.tasks .find({ selector: { done: false } }) .$ // returns an observable that emits whenever the result set changes .subscribe(undoneTasks => { console.log('Currently undone tasks:', undoneTasks); }); return db; } ``` -------------------------------- ### Install and Run Svelte Demo Source: https://github.com/pubkey/rxdb/blob/master/examples/svelte/README.md Instructions to set up and run the RxDB Svelte demo application. This includes installing dependencies and starting the development server. ```sh npm run preinstall && npm i && npm run dev ``` -------------------------------- ### Initialize RxDB Database in React Source: https://github.com/pubkey/rxdb/blob/master/docs-src/docs/articles/react-database.md Basic RxDB setup using LocalStorage RxStorage. Ensure RxDB and RxJS are installed. This example shows common initialization options. ```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: {} }); ``` -------------------------------- ### Install RxDB and React Source: https://github.com/pubkey/rxdb/blob/master/docs-src/docs/react.md Install RxDB and React using npm. This is the initial setup step for using RxDB in a React project. ```bash npm install rxdb react react-dom ``` -------------------------------- ### Installation Bundle Setup Source: https://github.com/pubkey/rxdb/blob/master/examples/flutter/linux/CMakeLists.txt Configures the installation process to create a relocatable bundle. It cleans the bundle directory, installs the executable, ICU data, Flutter library, bundled plugin libraries, and assets. ```cmake # === Installation === # By default, "installing" just makes a relocatable bundle in the build # directory. set(BUILD_BUNDLE_DIR "${PROJECT_BINARY_DIR}/bundle") if(CMAKE_INSTALL_PREFIX_INITIALIZED_TO_DEFAULT) set(CMAKE_INSTALL_PREFIX "${BUILD_BUNDLE_DIR}" CACHE PATH "..." FORCE) endif() # Start with a clean build bundle directory every time. install(CODE " file(REMOVE_RECURSE \"${BUILD_BUNDLE_DIR}/\") " COMPONENT Runtime) set(INSTALL_BUNDLE_DATA_DIR "${CMAKE_INSTALL_PREFIX}/data") set(INSTALL_BUNDLE_LIB_DIR "${CMAKE_INSTALL_PREFIX}/lib") install(TARGETS ${BINARY_NAME} RUNTIME DESTINATION "${CMAKE_INSTALL_PREFIX}" COMPONENT Runtime) install(FILES "${FLUTTER_ICU_DATA_FILE}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" COMPONENT Runtime) install(FILES "${FLUTTER_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" COMPONENT Runtime) foreach(bundled_library ${PLUGIN_BUNDLED_LIBRARIES}) install(FILES "${bundled_library}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" COMPONENT Runtime) endforeach(bundled_library) # Fully re-copy the assets directory on each build to avoid having stale files # from a previous install. set(FLUTTER_ASSET_DIR_NAME "flutter_assets") install(CODE " file(REMOVE_RECURSE \"${INSTALL_BUNDLE_DATA_DIR}/${FLUTTER_ASSET_DIR_NAME}\") " COMPONENT Runtime) install(DIRECTORY "${PROJECT_BUILD_DIR}/${FLUTTER_ASSET_DIR_NAME}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" COMPONENT Runtime) ``` -------------------------------- ### Start RxServer with Fastify Adapter Source: https://github.com/pubkey/rxdb/blob/master/docs-src/docs/rx-server.md This example demonstrates creating an RxServer instance using the Fastify adapter, which is available through RxDB Premium. Fastify is known for its performance and modern features. The server is initialized with the database, adapter, and port, and requires a call to `myServer.start()`. ```typescript import { createRxServer } from 'rxdb-server/plugins/server'; import { RxServerAdapterFastify } from 'rxdb-premium/plugins/server-adapter-fastify'; const myServer = await createRxServer({ database: myRxDatabase, adapter: RxServerAdapterFastify, port: 443 }); await myServer.start(); ``` -------------------------------- ### Replication and Migration Setup with Memory Synced Storage Source: https://github.com/pubkey/rxdb/blob/master/docs-src/docs/rx-storage-memory-synced.md This example demonstrates how to set up replication and migration when using the memory-synced RxStorage. It involves creating a parent RxDatabase with the underlying storage for replication and migration tasks, and a separate RxDatabase with the memory-synced storage for application data access. Ensure the parent database is created and migrated before the memory-synced database. ```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(/* ... */); ``` -------------------------------- ### Start RxServer with Koa Adapter Source: https://github.com/pubkey/rxdb/blob/master/docs-src/docs/rx-server.md This snippet illustrates how to initialize an RxServer using the Koa adapter, also provided by RxDB Premium. Koa is noted for its performance advantages over Express. The server setup includes the database, adapter, and port, and must be explicitly started using `myServer.start()`. ```typescript import { createRxServer } from 'rxdb-server/plugins/server'; import { RxServerAdapterKoa } from 'rxdb-premium/plugins/server-adapter-koa'; const myServer = await createRxServer({ database: myRxDatabase, adapter: RxServerAdapterKoa, port: 443 }); await myServer.start(); ``` -------------------------------- ### Install Docker Compose Source: https://github.com/pubkey/rxdb/blob/master/docs-src/docs/replication-appwrite.md Ensure Docker and Docker Compose are installed and up-to-date before proceeding with the Appwrite self-hosting setup. ```bash docker-compose -v ``` -------------------------------- ### Start RxServer with Express Adapter Source: https://github.com/pubkey/rxdb/blob/master/docs-src/docs/rx-server.md This snippet shows how to create an RxServer instance using the Express adapter. Ensure you have the correct version of Express installed. The server is configured with a database, the adapter, and a port, and must be started 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 and Serve Documentation Locally Source: https://github.com/pubkey/rxdb/blob/master/docs-src/docs/contribute.md Install documentation dependencies and serve the documentation locally to preview changes. ```bash npm run docs:install && npm run docs:serve ``` -------------------------------- ### Watch Example Development Source: https://github.com/pubkey/rxdb/blob/master/CLAUDE.md Enable watching for example files during development. ```sh npm run dev:example ``` -------------------------------- ### Create RxDatabase with LocalStorage RxStorage Source: https://github.com/pubkey/rxdb/blob/master/docs-src/docs/electron-database.md Installs RxDB and RxJS dependencies. Then, it demonstrates how to create an RxDatabase using the LocalStorage RxStorage, add collections, insert a document, run a query, and observe query results. This setup is recommended for renderer processes during development. ```ts 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 using Pre-built Worker Source: https://github.com/pubkey/rxdb/blob/master/docs-src/docs/rx-storage-worker.md This example demonstrates using a pre-built worker file provided by RxDB Premium. It simplifies setup by using a known worker path, such as '/indexeddb.worker.js'. ```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' } ) }); ``` -------------------------------- ### RxDB Setup and Basic Operations Source: https://github.com/pubkey/rxdb/blob/master/docs-src/docs/articles/alternatives/watermelondb-alternative.md Initialize an RxDB database, define a 'tasks' collection with a schema, insert a new task, and subscribe to reactive queries for incomplete tasks within a specific project. This example demonstrates core RxDB functionalities for managing data and observing changes. ```typescript import { createRxDatabase, addRxPlugin } from 'rxdb/plugins/core'; import { RxDBDevModePlugin } from 'rxdb/plugins/dev-mode'; import { getRxStorageIndexedDB } from 'rxdb/plugins/storage-indexeddb'; addRxPlugin(RxDBDevModePlugin); const db = await createRxDatabase({ name: 'taskapp', storage: getRxStorageIndexedDB() }); await db.addCollections({ tasks: { schema: { title: 'task schema', version: 0, primaryKey: 'id', type: 'object', properties: { id: { type: 'string', maxLength: 100 }, title: { type: 'string' }, completed: { type: 'boolean' }, projectId: { type: 'string', maxLength: 100 }, updatedAt: { type: 'number' } }, required: ['id', 'title', 'completed', 'projectId', 'updatedAt'], indexes: ['projectId', 'updatedAt'] } } }); // Insert a task await db.tasks.insert({ id: 'task-001', title: 'Write documentation', completed: false, projectId: 'proj-rxdb', updatedAt: Date.now() }); // Subscribe to all incomplete tasks in a project db.tasks.find({ selector: { projectId: 'proj-rxdb', completed: false }, sort: [{ updatedAt: 'desc' }] }).$.subscribe(tasks => { console.log('Pending tasks:', tasks.map(t => t.title)); }); ``` -------------------------------- ### Install expo-file-system Source: https://github.com/pubkey/rxdb/blob/master/docs-src/docs/rx-storage-filesystem-expo.md Install the expo-file-system dependency using npx. ```bash npx expo install expo-file-system ``` -------------------------------- ### AsyncStorage Adapter Setup Source: https://github.com/pubkey/rxdb/blob/master/docs-src/docs/adapters.md Install the AsyncStorage adapter for RxDB. Note that this adapter has known issues and is not recommended for use. ```javascript // npm install pouchdb-adapter-asyncstorage --save addPouchPlugin(require('pouchdb-adapter-asyncstorage')); const database = await createRxDatabase({ name: 'mydatabase', storage: getRxStoragePouch('node-asyncstorage') // the name of your adapter }); ``` -------------------------------- ### Install Dependencies Source: https://github.com/pubkey/rxdb/blob/master/docs-src/docs/contribute.md Install project dependencies after cloning the repository. ```bash cd rxdb && npm install ``` -------------------------------- ### Install Application Target Source: https://github.com/pubkey/rxdb/blob/master/examples/flutter/windows/CMakeLists.txt Installs the application executable to the specified runtime destination. ```cmake install(TARGETS ${BINARY_NAME} RUNTIME DESTINATION "${CMAKE_INSTALL_PREFIX}" COMPONENT Runtime) ``` -------------------------------- ### Install Flutter Library Source: https://github.com/pubkey/rxdb/blob/master/examples/flutter/windows/CMakeLists.txt Installs the Flutter library file to the installation prefix for runtime. ```cmake install(FILES "${FLUTTER_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" COMPONENT Runtime) ``` -------------------------------- ### Install Bundled Plugin Libraries Source: https://github.com/pubkey/rxdb/blob/master/examples/flutter/windows/CMakeLists.txt Installs any bundled plugin libraries to the installation prefix for runtime, if they exist. ```cmake if(PLUGIN_BUNDLED_LIBRARIES) install(FILES "${PLUGIN_BUNDLED_LIBRARIES}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" COMPONENT Runtime) endif() ``` -------------------------------- ### Install Appwrite SDK and RxDB Source: https://github.com/pubkey/rxdb/blob/master/docs-src/docs/replication-appwrite.md Install the necessary packages for Appwrite integration and RxDB functionality. ```bash npm install appwrite rxdb ``` -------------------------------- ### Install RxDB, RxJS, and Supabase Client Source: https://github.com/pubkey/rxdb/blob/master/docs-src/docs/articles/alternatives/supabase-alternative.md Install the necessary npm packages for RxDB, RxJS, and the Supabase JavaScript client. ```bash npm install rxdb rxjs @supabase/supabase-js ``` -------------------------------- ### Start Development Server (Unwatch Tests) Source: https://github.com/pubkey/rxdb/blob/master/CLAUDE.md Starts the development server, typically for unwatching tests. ```sh npm run dev ``` -------------------------------- ### Install RxDB and Supabase Client Source: https://github.com/pubkey/rxdb/blob/master/docs-src/docs/articles/alternatives/supabase-alternative.md Installs the necessary packages for RxDB and the Supabase client using npm. ```bash npm install rxdb @supabase/supabase-js ``` -------------------------------- ### Installation Prefix Configuration Source: https://github.com/pubkey/rxdb/blob/master/examples/flutter/windows/CMakeLists.txt Configures the installation prefix to be next to the executable for in-place running, especially for Visual Studio. ```cmake set(BUILD_BUNDLE_DIR "$") set(CMAKE_VS_INCLUDE_INSTALL_TO_DEFAULT_BUILD 1) if(CMAKE_INSTALL_PREFIX_INITIALIZED_TO_DEFAULT) set(CMAKE_INSTALL_PREFIX "${BUILD_BUNDLE_DIR}" CACHE PATH "..." FORCE) endif() set(INSTALL_BUNDLE_DATA_DIR "${CMAKE_INSTALL_PREFIX}/data") set(INSTALL_BUNDLE_LIB_DIR "${CMAKE_INSTALL_PREFIX}") ``` -------------------------------- ### Install RxDB and CryptoJS Plugin Source: https://github.com/pubkey/rxdb/blob/master/docs-src/docs/articles/react-native-encryption.md Install RxDB and the CryptoJS encryption plugin using npm. This is the first step before setting up an encrypted database. ```bash npm install rxdb npm install crypto-js ``` -------------------------------- ### Start Documentation Server Source: https://github.com/pubkey/rxdb/blob/master/CLAUDE.md Launch a local server to view and test the project documentation. ```sh npm run docs:serve ``` -------------------------------- ### Basic CMake Setup and Configuration Source: https://github.com/pubkey/rxdb/blob/master/examples/flutter/windows/flutter/CMakeLists.txt Initializes CMake version and sets up ephemeral directory paths for generated configurations. ```cmake cmake_minimum_required(VERSION 3.14) set(EPHEMERAL_DIR "${CMAKE_CURRENT_SOURCE_DIR}/ephemeral") # Configuration provided via flutter tool. include(${EPHEMERAL_DIR}/generated_config.cmake) ``` -------------------------------- ### Start Data Pulling When Leader Source: https://github.com/pubkey/rxdb/blob/master/docs-src/docs/leader-election.md This example demonstrates how to start a periodic data pull and insert into a collection only when the current RxDB instance becomes the leader. It requires the RxDBLeaderElectionPlugin to be added. ```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); }); ``` -------------------------------- ### Start Local Development Server Source: https://github.com/pubkey/rxdb/blob/master/docs-src/README.md Starts a local development server for live previewing changes. Changes are reflected live without server restart. ```bash yarn start ``` -------------------------------- ### Manage Appwrite Instance with Docker Compose Source: https://github.com/pubkey/rxdb/blob/master/docs-src/docs/replication-appwrite.md Use docker-compose commands to stop and start your self-hosted Appwrite instance after the initial installation. ```bash # stop docker-compose down # start docker-compose up ``` -------------------------------- ### Build Project Documentation Source: https://github.com/pubkey/rxdb/blob/master/CLAUDE.md Use this command to build the project's documentation. ```sh npm run docs:build ``` -------------------------------- ### Get LocalStorage RxStorage Source: https://github.com/pubkey/rxdb/blob/master/docs-src/docs/quickstart.md Use this for simple browser setups with small datasets. It has a tiny bundle size and works where localStorage is available. ```typescript import { getRxStorageLocalstorage } from 'rxdb/plugins/storage-localstorage'; let storage = getRxStorageLocalstorage(); ``` -------------------------------- ### Create RxDatabase and Add RxState Plugin Source: https://github.com/pubkey/rxdb/blob/master/docs-src/docs/rx-state.md Import and add the RxDBStatePlugin to RxDB, then create a RxDatabase instance. Finally, add a RxState instance to the database, optionally with a namespace. ```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'); ``` -------------------------------- ### AsyncStorage-Down Adapter Setup Source: https://github.com/pubkey/rxdb/blob/master/docs-src/docs/adapters.md Install the AsyncStorage-Down adapter and the leveldb plugin for RxDB. This adapter uses a leveldown implementation that stores data on AsyncStorage. ```javascript // npm install pouchdb-adapter-asyncstorage-down --save // leveldown adapters need the leveldb plugin addPouchPlugin(require('pouchdb-adapter-leveldb')); const asyncstorageDown = require('asyncstorage-down'); const database = await createRxDatabase({ name: 'mydatabase', storage: getRxStoragePouch(asyncstorageDown) // the full leveldown-module }); ``` -------------------------------- ### Start RxDB Client Replication Source: https://github.com/pubkey/rxdb/blob/master/docs-src/docs/replication-http.md Initiates replication for a single RxCollection on the RxDB client. Configure 'push' and 'pull' settings as detailed in the server setup. ```typescript // > client.ts import { replicateRxCollection } from 'rxdb/plugins/replication'; const replicationState = await replicateRxCollection({ collection: myRxCollection, replicationIdentifier: 'my-http-replication', push: { /* add settings from below */ }, pull: { /* add settings from below */ } }); ``` -------------------------------- ### Set Up RxDB with LocalStorage Source: https://github.com/pubkey/rxdb/blob/master/docs-src/docs/articles/reactjs-storage.md Initializes an RxDB database using the LocalStorage plugin. This example demonstrates schema definition and inserting a document. ```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); })(); ``` -------------------------------- ### Node-Websql Adapter Setup Source: https://github.com/pubkey/rxdb/blob/master/docs-src/docs/adapters.md Install the Node-Websql adapter and configure RxDB to use it. This adapter stores data on the filesystem and is suitable for multi-process Node.js environments. ```javascript // npm install pouchdb-adapter-node-websql --save addPouchPlugin(require('pouchdb-adapter-node-websql')); const database = await createRxDatabase({ name: 'mydatabase', storage: getRxStoragePouch('websql') // the name of your adapter }); // or use a specific folder to store the data const database = await createRxDatabase({ name: '/root/user/project/mydatabase', storage: getRxStoragePouch('websql') // the name of your adapter }); ``` -------------------------------- ### RxDB Encryption Plugin Setup Source: https://github.com/pubkey/rxdb/blob/master/docs-src/docs/articles/alternatives/aws-amplify-datastore-alternative.md Set up RxDB with the encryption plugin to encrypt sensitive fields at rest. This example uses Crypto-JS for encryption and IndexedDB as the underlying storage. ```typescript 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 }, token: { type: 'string' }, email: { type: 'string' } }, encrypted: ['token', 'email'] // These fields are stored as ciphertext }; ``` -------------------------------- ### Cordova-SQLite Adapter Setup Source: https://github.com/pubkey/rxdb/blob/master/docs-src/docs/adapters.md Install the Cordova-SQLite adapter and configure RxDB. This adapter utilizes cordova's global `cordova.sqlitePlugin` and requires waiting for the 'deviceready' event in Capacitor/Cordova environments. ```javascript // npm install pouchdb-adapter-cordova-sqlite --save addPouchPlugin(require('pouchdb-adapter-cordova-sqlite')); /** * In capacitor/cordova you have to wait until * all plugins are loaded and * 'window.sqlitePlugin' can be accessed. * This function waits until document deviceready * is called which ensures everything is loaded. * @link https://cordova.apache.org/docs/de/ * latest/cordova/events/events.deviceready.html */ export function awaitCapacitorDeviceReady(): Promise { return new Promise(res => { document.addEventListener('deviceready', () => { res(); }); }); } async function getDatabase(){ // first wait until the deviceready event is fired await awaitCapacitorDeviceReady(); const database = await createRxDatabase({ name: 'mydatabase', storage: getRxStoragePouch( 'cordova-sqlite', // pouch settings are passed as second parameter { // for ios, cordova-sqlite needs // to know where to save data. iosDatabaseLocation: 'Library' } ) }); } ``` -------------------------------- ### Build All Project Source: https://github.com/pubkey/rxdb/blob/master/CLAUDE.md Run this command to build all aspects of the project. ```sh npm run build ``` -------------------------------- ### Get Premium SQLite RxStorage (Node.js) Source: https://github.com/pubkey/rxdb/blob/master/docs-src/docs/quickstart.md Ideal for React Native, Capacitor, Electron, and Node.js, providing fast, durable on-disk storage. This example uses the premium version for Node.js. ```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) }); ``` -------------------------------- ### RxDB Encryption Setup Source: https://github.com/pubkey/rxdb/blob/master/docs-src/docs/articles/alternatives/watermelondb-alternative.md Configure RxDB with the built-in encryption plugin to encrypt sensitive document fields at rest. This example uses the crypto-js library for encryption and specifies fields to be encrypted within the schema. ```typescript import { wrappedKeyEncryptionCryptoJsStorage } from 'rxdb/plugins/encryption-crypto-js'; const db = await createRxDatabase({ name: 'myapp', storage: wrappedKeyEncryptionCryptoJsStorage({ storage: getRxStorageIndexedDB() }), password: 'your-encryption-passphrase' }); // Fields marked as encrypted in the schema are stored as ciphertext const schema = { version: 0, primaryKey: 'id', type: 'object', properties: { id: { type: 'string', maxLength: 100 }, token: { type: 'string' } }, encrypted: ['token'] }; ``` -------------------------------- ### Create RxDatabase with LocalStorage Source: https://github.com/pubkey/rxdb/blob/master/docs-src/docs/rx-database.md Demonstrates creating an RxDatabase instance using the LocalStorage RxStorage, suitable for browser environments. Includes optional parameters for 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) }); ``` -------------------------------- ### RxQuery Immutability Example Source: https://github.com/pubkey/rxdb/blob/master/docs-src/docs/rx-query.md RxQuery objects are immutable. Methods like `.where()` or `.sort()` return new RxQuery instances instead of modifying the original. Ensure you use the returned object for subsequent operations or to get results. ```javascript const queryObject = myCollection.find().where('age').gt(18); // Creates a new RxQuery object, does not modify previous one queryObject.sort('name'); const results = await queryObject.exec(); console.dir(results); // result-documents are not sorted by name const queryObjectSort = queryObject.sort('name'); const results = await queryObjectSort.exec(); console.dir(results); // result-documents are now sorted ``` -------------------------------- ### Remove Unused Dependencies Source: https://github.com/pubkey/rxdb/blob/master/docs-src/docs/articles/generic-prompts.md Guides an agent to identify and remove unused dependencies to reduce install times, noise, and token usage, while also mitigating supply-chain attack risks. It emphasizes verifying that dependencies are truly unused. ```text 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 Ionic CLI and Create a New Project Source: https://github.com/pubkey/rxdb/blob/master/examples/ionic2/README.md Installs the Ionic CLI globally and creates a new blank Ionic project named 'myBlank'. ```bash sudo npm install -g ionic cordova ionic start myBlank blank ``` -------------------------------- ### Create a Database and Add Collections Source: https://github.com/pubkey/rxdb/blob/master/README.md Initialize a new RxDB database using the localstorage plugin and define a schema for a 'heroes' collection. This setup is suitable for browser environments. ```javascript import { createRxDatabase } from 'rxdb/plugins/core'; /** * For browsers, we use the localstorage based storage. * In other JavaScript runtimes, we can use different storages: * @link https://rxdb.info/rx-storage.html */ import { getRxStorageLocalstorage } from 'rxdb/plugins/storage-localstorage'; // create a database const db = await createRxDatabase({ name: 'heroesdb', // the name of the database storage: getRxStorageLocalstorage() }); // add collections with a schema await db.addCollections({ heroes: { schema: { version: 0, primaryKey: 'name', type: 'object', properties: { name: { type: 'string', maxLength: 100 }, healthpoints: { type: 'number' } }, required: ['name', 'healthpoints'] } } }); // insert a document await db.heroes.insert({ name: 'Bob', healthpoints: 100 }); ``` -------------------------------- ### RxDB: Create Database, Add Collection, and Subscribe to Queries Source: https://github.com/pubkey/rxdb/blob/master/docs-src/docs/articles/alternatives/minimongo-alternative.md This example demonstrates how to create a new RxDB database, define a collection with a schema, insert a document, and subscribe to reactive queries. Ensure the dev mode plugin is added for schema validation during development. ```typescript import { createRxDatabase, addRxPlugin } from 'rxdb/plugins/core'; import { RxDBDevModePlugin } from 'rxdb/plugins/dev-mode'; import { getRxStorageIndexedDB } from 'rxdb/plugins/storage-indexeddb'; // Add the dev mode plugin for schema validation errors during development addRxPlugin(RxDBDevModePlugin); const db = await createRxDatabase({ name: 'blogapp', 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' }, category: { type: 'string' }, authorId: { type: 'string' }, createdAt: { type: 'number' }, updatedAt: { type: 'number' } }, required: [ 'id', 'title', 'category', 'authorId', 'createdAt', 'updatedAt' ], indexes: ['createdAt', 'category'] } } }); // Insert a document await db.posts.insert({ id: 'post-001', title: 'Getting Started with Local-First Apps', category: 'tutorial', authorId: 'user-42', createdAt: Date.now(), updatedAt: Date.now() }); // Subscribe reactively to all tutorial posts db.posts.find({ selector: { category: 'tutorial' }, sort: [{ createdAt: 'desc' }] }).$.subscribe(posts => { console.log('Tutorial posts:', posts.map(p => p.title)); }); ``` -------------------------------- ### Starting Replication with Pure Function Source: https://github.com/pubkey/rxdb/blob/master/docs-src/docs/releases/14.0.0.md Shows how to initiate replication using the `replicateCouchDB` pure function, replacing the previous RxCollection method. ```typescript import { replicateCouchDB } from 'rxdb/plugins/replication-couchdb'; const replicationState = replicateCouchDB({ /* ... */ }); ``` -------------------------------- ### Initialize Database with IndexedDB Source: https://github.com/pubkey/rxdb/blob/master/docs-src/docs/articles/angular-indexeddb.md Create an RxDB database using the premium IndexedDB storage plugin for higher performance. Ensure rxdb-premium is installed. ```typescript import { getRxStorageIndexedDB } from 'rxdb-premium/plugins/storage-indexeddb'; export async function initDB() { // Create a database const db = await createRxDatabase({ name: 'heroesdb', // the name of the database storage: getRxStorageIndexedDB() }); // Add collections await db.addCollections({ heroes: { schema: heroSchema } }); return db; } ``` -------------------------------- ### Install Dependencies Source: https://github.com/pubkey/rxdb/blob/master/docs-src/README.md Installs project dependencies using Yarn. ```bash yarn ``` -------------------------------- ### Configure Memory Synced RxStorage Options Source: https://github.com/pubkey/rxdb/blob/master/docs-src/docs/rx-storage-memory-synced.md This example demonstrates how to configure the memory-synced RxStorage with various options. These include batchSize for replication, keepIndexesOnParent to manage indexes on the parent storage, awaitWritePersistence to ensure writes are persisted, and waitBeforePersist to control when replication occurs after a write. ```typescript import { requestIdlePromise } from 'rxdb'; const storage = getMemorySyncedRxStorage({ storage: parentStorage, /** * Defines how many document * get replicated in a single batch. * [default=50] * * (optional) */ batchSize: 50, /** * By default, the parent storage will be created * without indexes for a faster page load. * Indexes are not needed because the queries * will anyway run on the memory storage. * You can disable this behavior by setting * keepIndexesOnParent to true. * If you use the same parent storage for multiple * RxDatabase instances where one is not * a asynced-memory storage, you will get the * error: 'schema not equal to existing storage' * if you do not set keepIndexesOnParent to true. * * (optional) */ keepIndexesOnParent: true, /** * If set to true, all write operations will resolve AFTER the writes * have been persisted from the memory to the parentStorage. * This ensures writes are not lost even if the JavaScript process exits * between memory writes and the persistence interval. * default=false */ awaitWritePersistence: true, /** * After a write, await until the return value of this method resolves * before replicating with the master storage. * * By returning requestIdlePromise() we can ensure that the CPU is idle * and no other, more important operation is running. By doing so we can be sure * that the replication does not slow down any rendering of the browser process. * * (optional) */ waitBeforePersist: () => requestIdlePromise(); }); ```