Dexie.js

repository·master·Indexed 12 days ago

https://github.com/dexie/dexie.js

A high-performance, minimalistic wrapper for IndexedDB that provides a developer-friendly API for managing client-side databases in the browser. Version 4.4.4 supports Electron, Capacitor, and PWAs, and includes an ecosystem of addons such as dexie-cloud-addon for real-time sync, dexie-export-import for database management, and y-dexie for Y.js integration.

Tokens
36.9K
Snippets
133
Records
161
Agent score
93%

What's inside Dexie.js

  1. Use dexie-react-hooks for React integration

    master
    The dexie-react-hooks library provides specialized React hooks designed to work with Dexie.js, enabling reactive UI updates when the underlying IndexedDB data changes. It is primarily used to implement 'Live Queries' in React applications, ensuring that components automatically re-render when the database is updated.
  2. Rules for Y properties on Dexie objects

    master

    When using y-dexie, keep the following rules in mind regarding Y.Doc properties:

    • Non-nullish: Y properties declared in the schema are never null or undefined. They exist on all objects returned by queries (e.g., toArray(), get()).
    • Prototype-level: They are not own properties of the object; they are set on the prototype.
    • Read-only properties: The property itself is read-only. You cannot replace the document instance or update it via Table.update() or Collection.modify(). You must use Y.Doc methods to mutate the content.
    • Lazy loading: Y.Doc data is not loaded until you use DexieYProvider.load() or the useDocument() hook.
    • Global Cache: Y.Doc instances are cached globally and tied to the parent object's primary key. Accessing the same property on different object instances representing the same ID will return the same Y.Doc instance.
  3. Configure UUID-based Primary Keys for Synchronization

    master

    Two-way replication requires that sync nodes can create objects while offline. Therefore, you cannot use auto-incremented keys. Instead, use the $$ prefix in your store schema to define primary keys as Universally Unique Identifiers (UUIDs) in string format.

    var db = new Dexie("MySyncedDB");
    db.version(1).stores({
        friends: "$$oid,name,shoeSize",
        pets: "$$oid,name,kind"
    });
  4. How the dexie-cloud-addon handles OAuth callbacks

    master

    The dexie-cloud-addon library simplifies the OAuth callback process for Web SPAs. When db.cloud.configure() is called in a DOM environment, the addon automatically checks the URL for a dxc-auth query parameter.

    If the parameter is present, the addon:

    1. Decodes the base64url-encoded JSON payload.
    2. Immediately cleans the URL using history.replaceState() to remove the sensitive dxc-auth parameter.
    3. Schedules the token exchange process to occur once Dexie is ready (within the db.on('ready') lifecycle).
  5. Understand the Dexie Export JSON format

    master

    The exported data is a JSON structure designed for streaming. To support streaming, the data property (containing the actual table rows) must appear last in the file. The format includes metadata about the database name, version, and table schemas.

    export interface DexieExportJsonStructure {
      formatName: 'dexie';
      formatVersion: 1;
      data: {
        databaseName: string;
        databaseVersion: number;
        tables: Array<{ 
          name: string; 
          schema: string; 
          rowCount: number; 
        }>;
        data: Array<{ 
          tableName: string; 
          inbound: boolean; 
          rows: any[]; // This property must be last
        }>;
      }
    }
  6. Use $$ prefix for auto-generated UUID primary keys

    master

    When defining stores in Version.stores(), you can use the $$ (double dollar) prefix for a primary key. This tells Dexie.Observable to automatically generate a UUID string for that key.

    Customizing UUID Generation

    Dexie adds a static method Dexie.createUUID() which is used internally for the $$ prefix. You can override this method to change the UUID format:

    Dexie.createUUID = function() {
      // Return your custom UUID format
      return 'custom-uuid-' + Date.now();
    };
    db.version(1).stores({
        friends: "$$uuid,name"
    });
  7. Quickstart Svelte with Dexie LiveQuery

    master

    To get started with Dexie.js in a Svelte application, you can use the liveQuery pattern to create reactive queries that automatically update your Svelte components when the underlying IndexedDB data changes.

    For a complete, interactive implementation, refer to the CodeSandbox example which demonstrates how to integrate Dexie's observable queries with Svelte's reactivity system.

    https://codesandbox.io/s/svelte-with-dexie-livequery-2n8bd?file=/App.svelte
  8. Use liveQuery with Angular Signals

    master

    To create reactive UI updates that respond to database changes, use Dexie's liveQuery() function. In Angular, you can convert the resulting observable into a Signal using toSignal() from @angular/core/rxjs-interop. This ensures the UI automatically updates whenever the underlying IndexedDB data changes.

    import { toSignal } from '@angular/core/rxjs-interop';
    import { from } from 'rxjs';
    import { liveQuery } from 'dexie';
    
    // In your component:
    items = toSignal(
      from(liveQuery(() => db.todoItems.toArray())),
      { initialValue: [] }
    );
  9. Install Dexie.Observable

    master

    To use Dexie.Observable, you must install both dexie and dexie-observable via npm.

    Note: This package is unmaintained and may be retired. For modern use cases, consider using Dexie's built-in liveQuery feature, which is not dependent on this package.

    npm install dexie --save
    npm install dexie-observable --save
  10. Set up Dexie.js with Angular

    master

    To use Dexie.js in an Angular project, define your database schema using Dexie and EntityTable for type safety. This example demonstrates a modern setup using standalone components and zoneless change detection.

    1. Install dependencies: npm install.
    2. Define your database schema in a dedicated file (e.g., db.ts).
    3. Run the application: npm start.
    npm install
    npm start
  11. Access and manipulate Y.Doc properties

    master

    To work with a Y.Doc property, you must load it using DexieYProvider.load(doc) and wait for provider.whenLoaded. Once loaded, you can use standard Y.js methods to manipulate the document. It is critical to call DexieYProvider.release(doc) when finished to manage the reference count and allow the document to be destroyed if no longer in use.

    import { db } from './db.js';
    import { DexieYProvider } from 'y-dexie';
    
    // 1. Fetch an object
    const friend = await db.friends.get(friendId);
    // 2. Get a reference to the notes Y.Doc
    const doc = friend.notes;
    // 3. Aquire a DexieYProvider
    const provider = DexieYProvider.load(doc);
    // 4. Load the document
    await provider.whenLoaded;
    
    // Manipulate
    doc.getText().insert(0, 'hello world');
    
    // 5. When done using the document, release it
    DexieYProvider.release(doc);