All files / storage/src/db db.ts

100% Statements 201/201
100% Branches 66/66
100% Functions 19/19
100% Lines 201/201

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 3441x 1x 1x   1x 1x 1x                         1x 116x 91x 91x 91x 91x 91x 91x 91x 91x 91x 135x   135x 84x 84x   84x 1x 1x   83x 91x 91x 84x 135x 131x 131x   131x 162x 162x 131x 135x 3x 3x   3x 4x 4x 3x   135x 135x 91x 12x   12x 6x 6x   12x 12x   12x 34x 34x 12x 91x   91x   91x 110x 25x 25x 25x 25x 25x 25x 25x 25x 116x                       1x         162x             162x 278x 278x         162x         162x         162x           162x 238x 238x             162x 162x 162x 162x 162x   162x 116x 116x   162x 1x 1x   162x 162x 162x                 162x 157x   157x 90x 90x   157x 101x 91x 91x 91x 1x 1x 1x 1x 101x 101x 16x 10x 10x   16x 16x 101x 101x 162x   96x 162x 95x 162x 1x 1x 1x   96x 101x 101x 4x 4x 4x 101x 149x 56x 18x 18x 18x   18x 18x 56x   56x 35x 35x   35x 35x 34x 35x 1x 1x 1x 1x 1x 1x 1x 35x 35x 35x 35x 55x 21x 21x 56x   157x 157x               162x 156x 156x 156x           162x 13x 13x           162x 64x 64x             162x 231x 97x 94x 94x 97x 231x             162x 93x 93x 91x 91x 93x                                               162x 94x 18x 18x   76x 76x 76x 76x 76x 76x 76x 76x 94x 162x   1x  
import { isFunction } from '@beerush/utils';
import { captureStack } from '@anchorlib/core';
import { type Connection, type DBEvent, type DBSubscriber, type DBUnsubscribe, IDBStatus } from './types.js';
 
export const DB_NAME = 'anchor';
export const DB_SYNC_DELAY = 100;
export const DB_CONNECTIONS = new Map<string, Connection>();
 
/**
 * Creates a new IndexedDB connection with the specified name and version.
 *
 * This function initializes a connection object that manages the IndexedDB lifecycle,
 * including opening, upgrading, loading, and closing the database. It handles all
 * the necessary event callbacks and maintains the connection state.
 *
 * @param name - The name of the database to connect to
 * @param version - The version number of the database schema
 * @returns A Connection object that represents the database connection
 */
const createConnection = (name: string, version: number): Connection => {
  if (hasIndexedDb()) {
    const connection = {
      name,
      version,
      status: IDBStatus.Idle,
      onUpgrade: new Set(),
      onLoaded: new Set(),
      onClosed: new Set(),
      onError: new Set(),
      open: () => {
        const request = indexedDB.open(connection.name, connection.version);
 
        request.onupgradeneeded = (event) => {
          const db = (event.target as IDBOpenDBRequest)?.result;
          const transaction = (event.target as IDBOpenDBRequest).transaction;
 
          if (!db || !transaction) {
            throw new Error(`Unable to upgrade database: ${connection.name}@${connection.version}.`);
          }
 
          for (const upgrade of connection.onUpgrade) {
            upgrade(event);
          }
        };
        request.onsuccess = async () => {
          connection.instance = request.result;
          connection.status = IDBStatus.Open;
 
          for (const load of connection.onLoaded) {
            await load(request.result);
          }
        };
        request.onerror = () => {
          connection.error = request.error;
          connection.status = IDBStatus.Closed;
 
          for (const reject of connection.onError) {
            reject(request.error);
          }
        };
 
        return connection;
      },
      close: (error) => {
        DB_CONNECTIONS.delete(connection.name);
 
        if (error) {
          connection.error = error;
        }
 
        connection.status = IDBStatus.Closed;
        connection.instance?.close();
 
        for (const close of connection.onClosed) {
          close(error);
        }
      },
    } as Connection;
 
    DB_CONNECTIONS.set(connection.name, connection);
 
    return connection;
  } else {
    return {
      name,
      version,
      error: new Error('IndexedDB is not available.'),
      status: IDBStatus.Closed,
      close: () => {},
    } as Connection;
  }
};
 
/**
 * IndexedStore is a class that manages IndexedDB connections and provides
 * a high-level interface for database operations. It handles connection
 * lifecycle management, including initialization, opening, closing, and
 * version upgrades.
 *
 * The class provides event subscription capabilities to monitor database
 * status changes and supports both synchronous and asynchronous setup
 * operations during database initialization.
 */
export class IndexedStore {
  /**
   * Set of subscribers that are notified of database status changes
   * @private
   */
  #subscribers = new Set<DBSubscriber>();
 
  /**
   * Gets the full connection name including the database name prefix
   * @protected
   * @returns The formatted connection name
   */
  protected get connectionName() {
    return `${DB_NAME}://${this.dbName}`;
  }
 
  /**
   * The underlying database connection object
   */
  public connection: Connection;
 
  /**
   * Current status of the database connection
   */
  public status = IDBStatus.Idle;
 
  /**
   * Error that occurred during database operations, if any
   */
  public error?: Error;
 
  /**
   * Gets the underlying IndexedDB database instance
   * @returns The IDBDatabase instance or undefined if not open
   */
  public get instance(): IDBDatabase | undefined {
    return this.connection.instance;
  }
 
  /**
   * Creates a new IndexedStore instance
   * @param dbName - The name of the database
   * @param version - The version of the database schema (default: 1)
   */
  constructor(
    protected dbName: string,
    protected version = 1
  ) {
    this.connection = DB_CONNECTIONS.get(this.connectionName) as Connection;
 
    if (!this.connection) {
      this.connection = createConnection(this.connectionName, version);
    }
 
    if (version > this.connection.version) {
      this.connection.version = version;
    }
 
    this.status = this.connection.status;
    this.error = this.connection.error as Error;
  }
 
  /**
   * Initializes the database connection by setting up event handlers
   * for upgrade, load, error, and close events. This method should be
   * called before opening the database.
   *
   * @returns This IndexedStore instance for method chaining
   */
  public init(): this {
    const connection = this.connection;
 
    if (connection.status === IDBStatus.Idle) {
      this.status = connection.status = IDBStatus.Init;
    }
 
    if (connection.status === IDBStatus.Init) {
      connection.onUpgrade.add((event: IDBVersionChangeEvent) => {
        try {
          this.upgrade?.(event);
        } catch (error) {
          this.error = error as Error;
          this.status = IDBStatus.Closed;
          this.finalize();
        }
      });
      connection.onClosed.add((error) => {
        if (error) {
          this.error = error;
        }
 
        this.status = IDBStatus.Closed;
        this.publish({ type: IDBStatus.Closed });
      });
      connection.onLoaded.add(async () => {
        if (this.status !== IDBStatus.Init) return;
 
        try {
          await this.setup?.();
          this.status = IDBStatus.Open;
        } catch (error) {
          this.error = error as Error;
          this.status = IDBStatus.Closed;
        }
 
        this.finalize();
      });
      connection.onError.add((error) => {
        this.error = error as Error;
        this.status = IDBStatus.Closed;
        this.finalize();
      });
    } else {
      this.connection.onClosed?.add((error) => {
        if (error) {
          this.error = error;
        }
 
        this.status = IDBStatus.Closed;
        this.publish({ type: IDBStatus.Closed });
      });
 
      if (connection.status === IDBStatus.Open) {
        (async () => {
          this.status = IDBStatus.Init;
 
          try {
            await this.setup?.();
            this.status = IDBStatus.Open;
          } catch (error) {
            captureStack.error.external(
              `Unable to finish the Database setup of "${this.dbName}".`,
              error as Error,
              this.init
            );
            this.error = error as Error;
            this.status = IDBStatus.Closed;
          } finally {
            this.finalize();
          }
        })();
      } else {
        this.finalize();
      }
    }
 
    return this;
  }
 
  /**
   * Opens the database connection. This method triggers the actual
   * IndexedDB open operation.
   *
   * @returns This IndexedStore instance for method chaining
   */
  public open(): this {
    this.connection?.open?.();
    return this;
  }
 
  /**
   * Closes the database connection
   * @param error - Optional error that caused the close
   */
  public close(error?: Error) {
    this.connection.close(error);
  }
 
  /**
   * Finalizes the initialization process by publishing the current status
   * @protected
   */
  protected finalize(): void {
    this.publish({ type: this.status });
  }
 
  /**
   * Publishes a database event to all subscribers
   * @param event - The database event to publish
   * @protected
   */
  protected publish(event: DBEvent) {
    for (const subscriber of this.#subscribers) {
      if (isFunction(subscriber)) {
        subscriber(event);
      }
    }
  }
 
  /**
   * Subscribes to database status changes
   * @param handler - The function to call when status changes
   * @returns A function to unsubscribe from status changes
   */
  public subscribe(handler: DBSubscriber): DBUnsubscribe {
    this.#subscribers.add(handler);
    return () => {
      this.#subscribers.delete(handler);
    };
  }
 
  /**
   * Optional method that is called when the database version needs to be upgraded.
   * Override this method in subclasses to define database schema changes.
   * @param event - The version change event
   * @protected
   */
  protected upgrade?(event: IDBVersionChangeEvent): void;
 
  /**
   * Optional method that is called after the database is opened.
   * Override this method in subclasses to perform any additional setup.
   * @protected
   */
  protected setup?(): Promise<void> | void;
 
  /**
   * Returns a promise that resolves when the database reaches either
   * the Open or Closed state. If the database is already in one of
   * these states, the promise resolves immediately.
   *
   * @returns A promise that resolves with the database event
   */
  public async promise(): Promise<DBEvent> {
    if (this.status !== IDBStatus.Init) {
      return { type: this.status };
    }
 
    return await new Promise((resolve) => {
      const unsubscribe = this.subscribe((event) => {
        if (event.type === IDBStatus.Open || event.type === IDBStatus.Closed) {
          resolve(event);
          unsubscribe();
        }
      });
    });
  }
}
 
const hasIndexedDb = () => typeof indexedDB !== 'undefined';