### Complete Dexie.js Setup and Examples Source: https://dexie.org/docs/MultiEntry-Index A comprehensive example demonstrating the setup of a Dexie database with a multiEntry index, insertion of data, and various querying methods including equals(), anyOf(), startsWithAnyOfIgnoreCase(), and OR conditions, along with the use of .distinct(). ```javascript // Define DB var db = new Dexie('dbname'); db.version(1).stores ({ books: 'id, author, name, *categories' }); // Insert a book of multiple categories db.books.put({ id: 1, name: 'Under the Dome', author: 'Stephen King', categories: ['sci-fi', 'thriller'] }); // Query all sci-fi books: function getSciFiBooks() { return db.books .where('categories').equals('sci-fi') .toArray (); } // Query all books of category 'sci-fi' or 'romance' function getSciFiOrRomanceBooks() { return db.books .where('categories').anyOf('sci-fi', 'romance') .distinct() // Never show 2 results of same book with both romance and sci-fi .toArray() } // Complex query function complexQuery() { return db.books .where('categories').startsWithAnyOfIgnoreCase('sci', 'ro') .or('author').equalsIgnoreCase('stephen king') .distinct() .toArray(); } ``` -------------------------------- ### Setting up Dexie with NPM and rollup Source: https://dexie.org/docs/Tutorial/Consuming-dexie-as-a-module Install Dexie and rollup. This example shows how to import Dexie and perform basic database operations using promises. ```javascript import { Dexie } from 'dexie'; var db = new Dexie('mydb'); db.version(1).stores({foo: 'id'}); db.foo.put({id: 1, bar: 'hello rollup'}).then(id => { return db.foo.get(id); }).then (item => { alert ("Found: " + item.bar); }).catch (err => { alert ("Error: " + (err.stack || err)); }); ``` -------------------------------- ### Setting up Dexie with NPM and webpack Source: https://dexie.org/docs/Tutorial/Consuming-dexie-as-a-module Install Dexie and webpack, then write a JavaScript file to interact with the database. This example demonstrates basic CRUD operations and querying. ```bash mkdir hello-dexie cd hello-dexie npm init --yes npm install dexie --save npm install webpack -g ``` -------------------------------- ### Complete Dexie Cloud Example with Encryption Source: https://dexie.org/docs/libs/dexie-encrypted A full example demonstrating the setup of Dexie with Dexie Cloud and the dexie-encrypted addon. It includes applying encryption, reordering middleware, and configuring Dexie Cloud. ```typescript import Dexie from 'dexie'; import dexieCloud from 'dexie-cloud-addon'; import { applyEncryptionMiddleware, encrypt } from 'dexie-encrypted'; const db = new Dexie('SecureCloudApp', { addons: [dexieCloud] }); // Apply encryption applyEncryptionMiddleware(db, encryptionKey, { messages: encrypt.NON_INDEXED_FIELDS, documents: { type: encrypt.ENCRYPT_LIST, fields: ['content', 'metadata'] } }); // Reorder encryption to run above sync function reorderDexieEncrypted(db: Dexie) { // @ts-ignore const mw = db._middlewares.dbcore.find(mw => mw.name === 'encryption'); if (!mw) throw new Error("Dexie encrypted not applied"); db.use({ name: "encryption", stack: "dbcore", level: 2, create: mw.create }); } reorderDexieEncrypted(db); // Configure Dexie Cloud db.cloud.configure({ databaseUrl: 'https://your-app.dexie.cloud', unsyncedTables: ['_encryptionSettings'], tryUseServiceWorker: false, // Recommended for encryption }); db.version(1).stores({ messages: '@id, title, category', documents: '@id, title, type' }); await db.open(); ``` -------------------------------- ### Start Development Server Source: https://dexie.org/docs/cloud/quickstart Start the application in development mode. ```bash npm run dev ``` -------------------------------- ### Start Database Replication Source: https://dexie.org/docs/cloud/premium-software Initiates a replication from a hosted Dexie Cloud database to a new local installation. Ensure DXC_SECRET and DXC_URL environment variables are set. ```bash npx dexie-cloud start-replication --from --to ``` -------------------------------- ### Install dexie-export-import Source: https://dexie.org/docs/ExportImport/dexie-export-import Install the dexie and dexie-export-import npm packages. ```bash npm install dexie npm install dexie-export-import ``` -------------------------------- ### Install Dexie Cloud SDK Source: https://dexie.org/docs/cloud/sdk Install the dexie-cloud-sdk package using npm. ```bash npm install dexie-cloud-sdk ``` -------------------------------- ### Install Dependencies Source: https://dexie.org/docs/dexie-react-hooks/usePermissions%28%29 Install the necessary packages for Dexie.js, React, and the Dexie Cloud addon. ```bash npm i react dexie dexie-cloud-addon dexie-react-hooks ``` ```bash yarn add react dexie dexie-cloud-addon dexie-react-hooks ``` -------------------------------- ### Install dexie-react-hooks with npm Source: https://dexie.org/docs/libs/dexie-react-hooks Install the library and its peer dependencies using npm. ```bash npm i react dexie dexie-react-hooks ``` -------------------------------- ### Basic Dexie.js Database Setup and Operations Source: https://dexie.org/docs/Tutorial/Hello-World This snippet shows how to initialize a Dexie database, define a 'friends' table with primary and secondary indexes, and perform bulk put operations. It then demonstrates querying for friends within an age range, retrieving all friends ordered by age in reverse, and finding friends whose names start with 'S'. ```html ``` -------------------------------- ### Dexie Worker Example Source: https://dexie.org/docs/Typescript Demonstrates the basic setup for using Dexie within a Web Worker for background database operations. ```typescript // worker.js import Dexie from 'dexie'; const db = new Dexie('myWorkerDB'); db.version(1).stores({ tasks: '++id, title, done' }); self.onmessage = async (event) => { if (event.data.type === 'ADD_TASK') { await db.tasks.add({ title: event.data.payload.title, done: false }); self.postMessage({ type: 'TASK_ADDED' }); } }; ``` -------------------------------- ### Install Dexie and Dexie Cloud Addon Source: https://dexie.org/docs/cloud/db.cloud.login%28%29 Install the necessary packages for Dexie and the Dexie Cloud addon using npm. ```bash npm i dexie dexie-cloud-addon ``` -------------------------------- ### Basic Encryption Setup with Dexie.js Source: https://dexie.org/docs/libs/dexie-encrypted Apply encryption middleware to a Dexie database before defining the schema. This example encrypts non-indexed fields while keeping indexed fields searchable. ```typescript import Dexie from 'dexie'; import { applyEncryptionMiddleware } from 'dexie-encrypted'; const db = new Dexie('MyDatabase'); // Apply encryption middleware before defining schema applyEncryptionMiddleware(db, symmetricKey, { friends: encrypt.NON_INDEXED_FIELDS, }); // Bump version when first adding encryption db.version(2).stores({ friends: '++id, name, age', }); await db.open(); const friend = { name: 'Alice', age: 25, street: 'East 13th Street', // Will be encrypted picture: 'alice.png', // Will be encrypted }; // Only non-indexed fields (street, picture) get encrypted // Indexed fields (id, name, age) remain searchable await db.friends.add(friend); ``` -------------------------------- ### Install dexie-react-hooks with yarn Source: https://dexie.org/docs/libs/dexie-react-hooks Install the library and its peer dependencies using yarn. ```bash yarn add react dexie dexie-react-hooks ``` -------------------------------- ### Dexie Worker Example Source: https://dexie.org/docs/Tutorial/Understanding-the-basics Demonstrates the basic setup and usage of a Dexie worker, which can be used for performing database operations off the main thread to improve application performance. ```javascript import DexieWorker from 'dexie-worker'; const worker = new DexieWorker('my-database-worker.js'); // Use worker for database operations worker.table('users').toArray().then(users => { console.log(users); }); ``` -------------------------------- ### Install Dependencies Source: https://dexie.org/docs/cloud/quickstart Install project dependencies using npm. This command should be run in the project's root directory. ```bash npm install ``` -------------------------------- ### Install Dexie.js with Yarn Source: https://dexie.org/docs/Download Use this command to install Dexie.js using the Yarn package manager. ```bash yarn add dexie ``` -------------------------------- ### Install Dexie.js with npm Source: https://dexie.org/docs/Download Use this command to install Dexie.js using the npm package manager. ```bash npm install dexie ``` -------------------------------- ### Install Dependencies Source: https://dexie.org/docs/dexie-react-hooks/useDocument%28%29 Install the necessary packages for Dexie, React, Dexie React Hooks, Yjs, and Y-Dexie. ```bash npm install react dexie dexie-react-hooks npm install yjs y-dexie ``` -------------------------------- ### Install Dexie and Dexie React Hooks Source: https://dexie.org/docs/Tutorial/React Install the Dexie database library and the Dexie React Hooks package using either yarn or npm. ```bash yarn add dexie yarn add dexie-react-hooks ``` ```bash npm install dexie npm install dexie-react-hooks ``` -------------------------------- ### LiveQuery Output Example Source: https://dexie.org/docs/liveQuery%28%29 Shows the expected console output when running the live query observable example, illustrating the sequence of results emitted as database changes occur. ```text Got result: [] 1. Adding friend Got result: [{"name":"Magdalena","age":54,"id":1}] 2. Changing age to 99 Got result: [] 3. Changing age to 55 Got result: [{"name":"Magdalena","age":55,"id":1}] 4. Setting property 'foo' to 'bar' Got result: [{"name":"Magdalena","age":55,"id":1,"foo":"bar"}] 5. Deleting friend Got result: [] ``` -------------------------------- ### Install Dexie-Encrypted for Dexie 3.x Source: https://dexie.org/docs/libs/dexie-encrypted Install the specific version of dexie-encrypted for Dexie 3.x projects. ```bash npm install dexie-encrypted@2.0.0 ``` -------------------------------- ### Install Dexie Dependencies Source: https://dexie.org/docs/Tutorial/Dexie-Cloud Install the core Dexie library, the Dexie Cloud addon, and the Dexie React hooks if you are using React. ```bash npm install dexie npm install dexie-cloud-addon npm install dexie-react-hooks # If you are using react ``` -------------------------------- ### Simple useLiveQuery Example Source: https://dexie.org/docs/dexie-react-hooks/useLiveQuery%28%29 A basic example demonstrating how to use useLiveQuery to fetch and display friends older than 75. The component re-renders automatically when the friends data changes. ```jsx import React from "react"; import { Dexie } from "dexie"; import { useLiveQuery } from "dexie-react-hooks"; import { db } from "./db"; // // React component // export function OldFriendsList() { const friends = useLiveQuery( () => db.friends .where('age') .above(75) .toArray() ); if (!friends) return null; // Still loading. return ; } ``` -------------------------------- ### Example New User Web Hook Request Source: https://dexie.org/docs/cloud/web-hooks An example of a complete HTTP POST request to a new user web hook endpoint, including headers and body. ```http POST /api/mywebhook2 HTTP/1.1 Host: yourapp.yourdomain.com Content-Type: application/json Content-Length: 54 {"userId":"foo@company.com","email":"bar@company.com"} ``` -------------------------------- ### Import File Example for Data Source: https://dexie.org/docs/cloud/cli An example of the JSON structure for importing or updating data within a specific realm and table. It shows how to define objects with their primary keys. ```json { "data": { "rlm-public": { "products": { "prd1": { "price": 60, "title": "Black T-shirt, size M", "description": "A nice black T-shirt (medium2)" }, "prd2": { "price": 70, "title": "Blue Jeans", "description": "Stone washed jeans" } } } } } ``` -------------------------------- ### Install Next Version of Dexie.js with npm Source: https://dexie.org/docs/Download Use this command to install the next release of Dexie.js using the npm package manager. ```bash npm install dexie@next ``` -------------------------------- ### Install RxJS and VueUse RxJS Source: https://dexie.org/docs/Tutorial/Vue Install necessary libraries for handling observables in Vue. RxJS is used for reactive programming, and VueUse RxJS helps integrate observables with Vue's reactivity system. ```bash npm install rxjs npm install @vueuse/rxjs ``` -------------------------------- ### List Users HTTP Example Source: https://dexie.org/docs/cloud/rest-api Example of an HTTP request to list users with specific sorting and limit, and its corresponding JSON response. ```http GET /users?sort=userId&limit=2 HTTP/1.1 Host: xxxx.dexie.cloud Authorization: Bearer XXX... HTTP/1.1 200 Ok Content-Type: application/json { "data": [ { "created": "2023-10-27T22:10:29.922Z", "data": null, "deactivated": null, "lastLogin": "2023-10-31T08:22:56.816Z", "type": "demo", "updated": "2023-10-27T22:10:29.922Z", "userId": "alice@demo.local" }, { "created": "2023-10-30T13:45:24.993Z", "data": { "email": "david@dexie.org", "displayName": "David Fahlander" }, "deactivated": null, "evalDaysLeft": 30, "lastLogin": "2023-10-30T14:45:04.051Z", "maxAllowedEvalDaysLeft": 30, "type": "eval", "updated": "2023-10-30T13:45:24.981Z", "userId": "david@dexie.org" } ], "hasMore": true, "pagingKey": "WyJhbGljZUBkZW1vLmxvY2FsIiwiYWxpY2VAZGVtby5sb2NhbCJd" } ``` -------------------------------- ### Example New User Web Hook Response Source: https://dexie.org/docs/cloud/web-hooks An example of a successful HTTP response from a new user web hook endpoint, indicating the user is approved for production. ```http HTTP/1.1 200 Ok Content-Type: application/json Content-Length: 27 {"ok":true,"action":"prod"} ``` -------------------------------- ### Example Web Hook Request - Update Source: https://dexie.org/docs/cloud/web-hooks Demonstrates an example POST request to a web hook endpoint when an object is partially updated in Dexie Cloud. ```http POST /api/mywebhook HTTP/1.1 Host: yourapp.yourdomain.com Content-Type: application/json X-DexieCloud-Token: 3IFLLLQAHGIN32PCETPWVG2E5A { "changes": [ { "type": "update", "realmId": "foo@bar.com", "table": "todoItems", "key": "tdi0Ph7h|YdzM77VzcMigVJrbRZcal", "updates": { "done": true } } ] } ``` -------------------------------- ### Get Single User HTTP Example Source: https://dexie.org/docs/cloud/rest-api Example of an HTTP request to retrieve a single user and its corresponding JSON response. ```http GET /users/alice@demo.local HTTP/1.1 Host: xxxx.dexie.cloud Authorization: Bearer XXX... HTTP/1.1 200 Ok Content-Type: application/json { "created" : "2023-10-27T22:10:29.922Z", "data" : null, "deactivated" : null, "evalDaysLeft" : 0, "lastLogin" : "2023-10-31T08:22:56.816Z", "maxAllowedEvalDaysLeft" : 0, "type" : "demo", "updated" : "2023-10-27T22:10:29.922Z", "userId" : "alice@demo.local" } ``` -------------------------------- ### Importing Dexie as a module Source: https://dexie.org/docs/Tutorial/Consuming-dexie-as-a-module Import Dexie and initialize a database with a schema. This is a common setup for web applications. ```javascript import { Dexie } from 'dexie'; const db = new Dexie('myDb'); db.version(1).stores({ friends: `name, age` }); export default db; ``` ```javascript import db from './mydatabase'; ``` -------------------------------- ### Get User-Accessible Todo Lists Source: https://dexie.org/docs/cloud/rest-api An example of retrieving user-accessible todoLists, including private and shared lists. Requires an ACCESS_DB scope. ```http GET /my/todoLists HTTP/1.1 Host: xxxx.dexie.cloud Authorization: Bearer ``` -------------------------------- ### Sample: Create Dexie Cloud database Source: https://dexie.org/docs/cloud/cli Example of the interactive prompts and output when creating a new database, including the generation of local configuration files. ```bash $ npx dexie-cloud create Enter your email address: youremail@company.com Enter OTP: YourOTP Creating database... Successfully created new database! We created two new local files for you: ======================================= dexie-cloud.json - URL to database dexie-cloud.key - contains client ID and secret ``` -------------------------------- ### Sample: Connect to Dexie Cloud database Source: https://dexie.org/docs/cloud/cli Example of the interactive prompts and output when connecting to an existing database, including the update of local configuration files. ```bash $ npx dexie-cloud connect https://zrp8lv7rq.dexie.cloud Enter your email address: youremail@company.com Enter OTP: YourOTP Successful client confirmation. Local files have been updated: ============================== dexie-cloud.json - URL to database dexie-cloud.key - contains client ID and secret ``` -------------------------------- ### Prepare Release Environment Source: https://dexie.org/docs/Releasing-Dexie Navigate to the dedicated release clone, check the working directory status, checkout the master branch, pull the latest changes, and install dependencies. ```shell cd /c/repos/dexie-release # or dexie-release-1 for maintenance releases o 1.x. git status # Make sure your working directory is clean git checkout master # Or master-1 for maintenance release of 1.x. git pull # Pull latest git status # Make sure your working directory is still clean. npm install # Makes sure to install added deps ``` -------------------------------- ### Dexie.on.populate() Sample Source: https://dexie.org/docs/Dexie/Dexie.on.populate-%28old-version%29 This sample demonstrates how to populate initial data into a database using the on('populate') event when the database is first created. ```javascript var db = new Dexie("MyDB"); db.version(1).stores({friends: "id++,name,gender"}); db.on("populate", function() { db.friends.add({name: "Josephina", gender: "unisex"}); }); db.open(); ``` -------------------------------- ### Configure Application Script Source: https://dexie.org/docs/cloud/quickstart Make the configuration script executable and then run it to configure the application and database. ```bash chmod +x ./configure-app.sh ./configure-app.sh ``` -------------------------------- ### Get All Todo Items by Todo List ID Source: https://dexie.org/docs/cloud/rest-api A concrete example of filtering objects, retrieving all todoItems associated with a specific todoListId. Requires GLOBAL_READ and ACCESS_DB scopes. ```http GET /all/todoItems?todoListId=xxx HTTP/1.1 Host: xxxx.dexie.cloud Authorization: Bearer ``` -------------------------------- ### Dexie Cloud Setup and Configuration Source: https://dexie.org/docs/API-Reference Commands to create a Cloud Database and whitelist an origin. Also shows how to import and configure the dexie-cloud-addon with your Dexie database. ```bash # Create a Cloud Database npx dexie-cloud create # Whitelist Origin npx dexie-cloud whitelist http://localhost:3000 ``` ```javascript // // Use dexie-cloud-addon with your DB: // import dexieCloud, { type DexieCloudTable } from 'dexie-cloud-addon'; import { dbUrl } from '../../dexie-cloud.json'; // Or use an ENV var... const db = new Dexie('syncedDB', { addons: [dexieCloud]}) as Dexie & { // Get nice and concise typings: friends: DexieCloudTable } db.version(1).stores({ friends: 'id, name, age' // Or use @id to autogenerate }); db.cloud.configure({ databaseUrl: dbUrl, requireAuth: true // or false to sync eventually on login }); ``` -------------------------------- ### Initialize Dexie Cloud Server Source: https://dexie.org/docs/cloud/premium-software Initializes the Dexie Cloud server, setting up the SQL schema and tables. This command also creates the dexie-cloud.json and dexie-cloud.key files. ```bash export DXC_SECRET= export DXC_URL= npm run init-cloud ``` -------------------------------- ### Define Database Schema (JavaScript) Source: https://dexie.org/docs/Tutorial/Vue Create a Dexie instance and define your database schema with tables and indexes. This JavaScript example shows a basic setup for a 'friends' table. ```javascript // db.js import { Dexie } from 'dexie'; export const db = new Dexie('myDatabase'); db.version(1).stores({ friends: '++id, name, age', }); ``` -------------------------------- ### Querying with Partial Compound Indexes Source: https://dexie.org/docs/Compound-Index Demonstrates how Dexie allows using parts of compound indexes for queries. These queries have the side effect of sorting by the trailing property. Examples include getting all people by 'firstName' (sorted by lastName) or by 'lastName' (sorted by firstName). ```javascript // Get all Annas, order by lastname. db.people.where({firstName: "Anna"}).toArray() ``` ```javascript // Get all Larsons, order by firstName. db.people.where({lastName: "Larson"}).toArray() ``` -------------------------------- ### Initialize Git Repository Source: https://dexie.org/docs/cloud/quickstart Initialize a new Git repository and commit the project files. ```bash git init git add . git commit -m "Initial commit" ``` -------------------------------- ### Complex MultiEntry Index Query Source: https://dexie.org/docs/MultiEntry-Index Perform a complex query on multiEntry indexes using startsWithAnyOfIgnoreCase and OR conditions. This example queries for books whose categories start with 'sci' or 'ro' (case-insensitive), or books authored by 'stephen king' (case-insensitive). .distinct() is used to avoid duplicate results. ```javascript // Complex query function complexQuery() { return db.books .where('categories').startsWithAnyOfIgnoreCase('sci', 'ro') .or('author').equalsIgnoreCase('stephen king') .distinct() .toArray(); } ``` -------------------------------- ### Quick Start with Dexie Cloud Client Source: https://dexie.org/docs/cloud/sdk Initialize the Dexie Cloud client and database session, then perform basic data operations. Tokens are managed automatically. ```typescript import { DexieCloudClient } from 'dexie-cloud-sdk'; import { readFileSync } from 'fs'; // Read credentials from dexie-cloud.key (generated by `npx dexie-cloud connect`) const keys = JSON.parse(readFileSync('dexie-cloud.key', 'utf-8')); const dbUrl = Object.keys(keys)[0]; const { clientId, clientSecret } = keys[dbUrl]; // Create client and database session const client = new DexieCloudClient('https://dexie.cloud'); const db = client.db(dbUrl, { clientId, clientSecret }); // Use it — no tokens to manage! const items = await db.data.list('todoItems'); await db.data.create('todoItems', { title: 'Buy milk', done: false }); ``` -------------------------------- ### Local web server for testing Source: https://dexie.org/docs/Tutorial/Consuming-dexie-as-a-module Install and run http-server to serve the current directory, which is useful for testing web applications that use IndexedDB, as direct file access can be restricted. ```bash npm install -g http-server http-server . ``` -------------------------------- ### Build and Deploy PWA to GitHub Pages Source: https://dexie.org/docs/cloud/quickstart Build the PWA for deployment and then deploy it to GitHub Pages. This also includes whitelisting the deployed origin. ```bash npm run build # Deploy the PWA to GitHub Pages: npm run deploy # White-list the origin: npx dexie-cloud whitelist https://.github.io ``` -------------------------------- ### Compound Key Operations (get, put, update) Source: https://dexie.org/docs/Compound-Index Demonstrates using compound keys as arrays for operations like get(), put(), and update(). Also shows using object queries for get(). ```javascript const db = new Dexie('compoundDemo'); db.version(1).stores({ people: '[firstName+lastName]' }); db.people.put({ firstName: "Anna", lastName: "Larsson" }).then(() => { // Key arguments should be the compound array: return db.people.get(["Anna", "Larsson"]); }).then(anna => { // For Table.get(), it is also possible to use object queries: return db.people.get({ firstName: "Anna", lastName: "Larsson" }); }).then(anna => { console.log(anna); }).then(()=>{ // Provide Array to Table.update(): return db.people.update(["Anna", "Larsson"], { foo: "bar" }); }).catch(console.error); ``` -------------------------------- ### Example: Delete a todoItem Source: https://dexie.org/docs/cloud/rest-api Example of deleting a specific todo item using its ID. ```HTTP DELETE /all/todoItems/tdi0Oma0cOxZhnmTbCQTMxP3Xetcal HTTP/1.1 Host: z0lesejpr.dexie.cloud Authorization: Bearer ``` -------------------------------- ### List and connect to Dexie Cloud databases Source: https://dexie.org/docs/cloud/cli View a list of databases you have credentials for and switch between them using the 'connect' command. ```bash $ npx dexie-cloud databases https://z7sk70jbj.dexie.cloud https://zdmrn79uu.dexie.cloud <--current $ npx dexie-cloud connect https://z7sk70jbj.dexie.cloud Current database is now https://z7sk70jbj.dexie.cloud (stored in dexie-cloud.json) $ npx dexie-cloud databases https://z7sk70jbj.dexie.cloud <--current https://zdmrn79uu.dexie.cloud ``` -------------------------------- ### LiveQuery Observable Example Source: https://dexie.org/docs/liveQuery%28%29 Demonstrates setting up a live query for friends within a specific age range and subscribing to its results. It shows how adding, updating, and deleting friends triggers observable emissions. ```javascript import { liveQuery } from 'dexie'; import { db } from './db'; const friendsObservable = liveQuery(() => db.friends.where('age').between(50, 75).toArray() ); const subscription = friendsObservable.subscribe({ next: (result) => console.log('Got result:', JSON.stringify(result)), error: (error) => console.error(error) }); const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); await sleep(1000); console.log('1. Adding friend'); const friendId = await db.friends.add({ name: 'Magdalena', age: 54 }); await sleep(1000); console.log('2. Changing age to 99'); await db.friends.update(friendId, { age: 99 }); await sleep(1000); console.log('3. Changing age to 55'); await db.friends.update(friendId, { age: 55 }); await sleep(1000); console.log("4. Setting property 'foo' to 'bar'"); await db.friends.update(friendId, { foo: 'bar' }); await sleep(1000); console.log('5. Deleting friend'); await db.friends.delete(friendId); subscription.unsubscribe(); ``` -------------------------------- ### Configure Dexie Cloud with Blob Offloading Source: https://dexie.org/docs/cloud/blob-offloading This snippet shows the basic setup for Dexie Cloud, including enabling the addon and configuring the database URL. It also demonstrates storing a file object, which will be automatically offloaded. ```javascript import Dexie from 'dexie'; import dexieCloud from 'dexie-cloud-addon'; const db = new Dexie('mydb', { addons: [dexieCloud] }); db.version(1).stores({ photos: '@id, title, date' }); db.cloud.configure({ databaseUrl: 'https://xxxxxxxx.dexie.cloud', requireAuth: true }); // Store a photo with binary data — offloading happens automatically on sync const file = document.querySelector('input[type=file]').files[0]; await db.photos.add({ title: 'My Photo', date: new Date(), image: file // Blob — will be offloaded to blob storage }); ``` -------------------------------- ### Get Single User Request Source: https://dexie.org/docs/cloud/rest-api Use this GET request to retrieve a specific user by their userId. ```http GET /users/ HTTP/1.1 Authorization: Bearer ``` -------------------------------- ### Example: Delete a compound key Source: https://dexie.org/docs/cloud/rest-api Example of deleting an object with a compound primary key, which is URI encoded. ```HTTP DELETE /all/compoundTable/%5B%22Bob%22%2C42%5D HTTP/1.1 Host: xxxx.dexie.cloud Authorization: Bearer ``` -------------------------------- ### Real-time Friend List with useLiveQuery Source: https://dexie.org/docs/dexie-react-hooks/useLiveQuery%28%29 This example demonstrates how to use useLiveQuery to fetch and display a list of friends, updating in real-time as data changes. It shows dynamic querying based on state and handling loading states. ```javascript import React, { useState } from "react"; import { useLiveQuery } from "dexie-react-hooks"; import { db } from "../db"; export function FriendList() { const [maxAge, setMaxAge] = useState(21); // Query friends within a certain range decided by state: const friends = useLiveQuery( () => db.friends.where("age").belowOrEqual(maxAge).sortBy("id"), [maxAge] // because maxAge affects query! ); // Example of another query in the same component. const friendCount = useLiveQuery(() => db.friends.count()); // If default values are returned, queries are still loading: if (!friends || friendCount === undefined) return null; return (

Your have {friendCount} friends in total.

    {friends.map((friend) => (
  • {friend.name}, {friend.age}
  • ))}
); } ``` -------------------------------- ### Get Public Data Source: https://dexie.org/docs/cloud/rest-api Retrieves public data from the `rlm-public` realm. This endpoint does not require authorization for GET requests. ```APIDOC ## GET /public/ ### Description Retrieves public data from the `rlm-public` realm. This endpoint does not require authorization for GET requests. ### Method GET ### Endpoint /public/
### Request Example ``` GET /public/products HTTP/1.1 GET /public/roles HTTP/1.1 ``` ### Response Returns public data from the specified table. ``` -------------------------------- ### Example JSON Export File Structure Source: https://dexie.org/docs/ExportImport/dexie-export-import This is an example of the JSON structure used for exporting Dexie database data. ```json { "formatName": "dexie", "formatVersion": 1, "data": { "databaseName": "dexie-export-import-basic-tests", "databaseVersion": 1, "tables": [ { "name": "outbound", "schema": "", "rowCount": 2 }, { "name": "inbound", "schema": "++id", "rowCount": 3 } ], "data": [{ "tableName": "outbound", "inbound": false, "rows": [ [ 1, { "foo": "bar" } ], [ 2, { "bar": "foo" } ] ] },{ "tableName": "inbound", "inbound": true, "rows": [ { "id": 1, "date": 1, "fullBlob": { "type": "", "data": "AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8gISIjJCUmJygpKissLS4vMDEyMzQ1Njc4OTo7PD0+P0BBQkNERUZHSElKS0xNTk9QUVJTVFVWV1hZWltcXV5fYGFiY2RlZmdoaWprbG1ub3BxcnN0dXZ3eHl6e3x9fn+AgYKDhIWGh4iJiouMjY6PkJGSk5SVlpeYmZqbnJ2en6ChoqOkpaanqKmqq6ytrq+wsbKztLW2t7i5uru8vb6/wMHCw8TFxsfIycrLzM3Oz9DR0tPU1dbX2Nna29zd3t/g4eLj5OXm5+jp6uvs7e7v8PHy8/T19vf4+fr7/P3+/w==" }, "binary": { "buffer": "AQID", "byteOffset": 0, "length": 3 }, "text": "foo", "bool": false, "$types": { "date": "date", "fullBlob": "blob2", "binary": "uint8array2", "binary.buffer": "arraybuffer" } }, { "id": 2, "foo": "bar" }, { "id": 3, "bar": "foo" } ] }] } } ``` -------------------------------- ### Create a demoUsers.json file Source: https://dexie.org/docs/cloud/add-demo-users Create a JSON file named 'demoUsers.json' to define the demo users you want to import. Each user is identified by their email address. ```json { "demoUsers": { "alice@demo.local": {}, "bob@demo.local": {} } } ``` -------------------------------- ### Get Public Data from a Table Source: https://dexie.org/docs/cloud/rest-api Retrieves public data from a specified table. This endpoint does not require authorization for GET requests. ```http GET /public/products HTTP/1.1 ``` ```http GET /public/roles HTTP/1.1 ``` -------------------------------- ### Initialize Dexie with Dexie Cloud Add-on Source: https://dexie.org/docs/cloud/dexie-cloud-addon Import and include the dexie-cloud-addon in your Dexie instance. Configure the database URL and other options for cloud synchronization. ```javascript import { Dexie } from 'dexie' import dexieCloud from 'dexie-cloud-addon' // Import the addon const db = new Dexie('mydb', { addons: [dexieCloud], // Include addon in your Dexie instance }) db.version(1).stores({ myTable: '@myId, myIndex1, myIndex2, ...', }) db.cloud.configure({ databaseUrl: 'https://xxxxxxx.dexie.cloud', // URL from `npx dexie-cloud create` ...otherOptions, }) ``` -------------------------------- ### Entity Class Example Source: https://dexie.org/docs/Typescript An example of an entity class with methods that can access the database. It extends Dexie's Entity class. ```typescript // Friend.ts import { Entity } from "dexie" import type AppDB from "./AppDB" export default class Friend extends Entity { id!: number name!: string age!: number // example method that access the DB: async birthday() { // this.db is inherited from Entity: await this.db.friends.update(this.id, (friend) => ++friend.age) } } ``` -------------------------------- ### Dexie: Catching Thrown Exceptions Example Source: https://dexie.org/docs/Promise/Promise.catch%28%29 An example showing how to catch exceptions that are thrown after a promise has resolved, using .catch() to handle them. ```javascript var db = new Dexie('db'); db.version(1).stores({friends: 'email,name'}); db.open(); db.friends.add({email: "abc@def.com", name: "Gertrud"}).then(function() { throw new Error ("Ha ha ha!"); }).catch (function (e) { alert ("Failed: " + e.toString()); }); ``` -------------------------------- ### Example Web Hook Request - Delete Source: https://dexie.org/docs/cloud/web-hooks Demonstrates an example POST request to a web hook endpoint when an object is deleted in Dexie Cloud. ```http POST /api/mywebhook HTTP/1.1 Host: yourapp.yourdomain.com Content-Type: application/json X-DexieCloud-Token: 3IFLLLQAHGIN32PCETPWVG2E5A { "changes": [ { "type": "delete", "realmId": "foo@bar.com", "table": "todoItems", "key": "tdi0Ph7h|YdzM77VzcMigVJrbRZcal" } ] } ``` -------------------------------- ### Basic Login and Pre-filled Email Source: https://dexie.org/docs/cloud/db.cloud.login%28%29 Demonstrates how to initiate a login flow, either by showing a dialog or pre-filling an email for OTP login. ```javascript // Show login dialog and wait for user to complete authentication await db.cloud.login(); // Pre-fill email for OTP login await db.cloud.login({ email: 'someone@company.com' }); ``` -------------------------------- ### Dexie: Catching Error Events Example Source: https://dexie.org/docs/Promise/Promise.catch%28%29 A complete example demonstrating how to add a friend and catch potential errors during the operation using .catch(). ```javascript var db = new Dexie('db'); db.version(1).stores({friends: 'email,name'}); db.open(); // Un-remark following line to make it fail due to ConstraintError: // db.friends.add({email: "abc@def.com", name: "Oliver"}); db.friends.add({email: "abc@def.com", name: "Gertrud"}).then(function() { alert ("Successfully added friend into DB"); }).catch (function (e) { alert ("Failed to add friend into DB: " + e); }); ```