feat: implement PouchDB storage layer with CRUD operations and add showcase UI component
This commit is contained in:
+99
-126
@@ -2,167 +2,140 @@
|
||||
|
||||
[← Back to Root](../../README.md)
|
||||
|
||||
The **Enterprise-grade storage engine** for the monorepo.
|
||||
This package provides an **Offline-First Storage Engine** using PouchDB, tailored for Enterprise React applications. It is built to seamlessly sync with remote CouchDB instances, providing full fault tolerance and offline capabilities.
|
||||
|
||||
This package provides a unified, Factory-based interface for interacting with browser storage (`localStorage` and `IndexedDB`). It enforces strict type safety, **Runtime Validation**, App Autonomy (Inversion of Control), and automatically provides **AES encryption at rest** for sensitive payloads (like access tokens) using `@repo/utils`.
|
||||
## High-Level Overview
|
||||
|
||||
---
|
||||
|
||||
## Architecture & Data Flow
|
||||
Our storage architecture enforces strict **Inversion of Control (IoC)**. The core engine (`@repo/core-storage`) is a pure factory—it knows absolutely nothing about your business domains, data models, or specific databases. Consuming applications (like `apps/web`) dictate the rules by injecting their specific configurations and generic types into the storage engine.
|
||||
|
||||
```mermaid
|
||||
graph TD
|
||||
subgraph Apps ["apps/* (App Autonomy)"]
|
||||
REG[[AppStorageKey & App Registries]]
|
||||
UI[React Components / API Interceptors]
|
||||
INST{{Storage Instances}}
|
||||
subgraph UI ["Consuming App (apps/*)"]
|
||||
COMP["React Components / Forms"]
|
||||
end
|
||||
|
||||
subgraph Core ["@repo/core-storage (Engine Factories)"]
|
||||
API[IStorageService API]
|
||||
FAC[createLocalStorage / createIndexedDB]
|
||||
VAL{Runtime Gatekeeper}
|
||||
ENC{{AES Encryption Pipeline}}
|
||||
LOCAL[LocalStorage Adapter]
|
||||
IDB[IndexedDB Adapter]
|
||||
subgraph CoreStorage ["@repo/core-storage Engine"]
|
||||
MGR["PouchDatabaseManager Factory"]
|
||||
L_SALES[("Local PouchDB: Sales")]
|
||||
L_INV[("Local PouchDB: Inventory")]
|
||||
end
|
||||
|
||||
subgraph Browser ["Browser APIs (Native)"]
|
||||
B_LOCAL[(localStorage)]
|
||||
B_IDB[(IndexedDB)]
|
||||
subgraph RemoteServer ["CouchDB Cluster (Cloud/On-Prem)"]
|
||||
R_SALES[("Remote CouchDB: sales_db")]
|
||||
R_INV[("Remote CouchDB: inventory_db")]
|
||||
end
|
||||
|
||||
REG -.->|Injects Keys & Config| FAC
|
||||
FAC --> INST
|
||||
UI -->|getItem / setItem| INST
|
||||
INST --> API
|
||||
API --> VAL
|
||||
|
||||
VAL -.->|Valid Key?| ENC
|
||||
VAL -.->|Invalid Key!| ERR[Throws Security Exception]
|
||||
|
||||
ENC -.->|Sensitive Key| LOCAL & IDB
|
||||
VAL -.->|Plain-text Key| LOCAL & IDB
|
||||
COMP -->|Read / Write| L_SALES
|
||||
COMP -->|Read / Write| L_INV
|
||||
MGR -->|Instantiates Multi-DB| L_SALES
|
||||
MGR -->|Instantiates Multi-DB| L_INV
|
||||
|
||||
LOCAL <--> B_LOCAL
|
||||
IDB <--> B_IDB
|
||||
|
||||
%% Styling Subgraphs
|
||||
style Apps fill:#e7f5ff,stroke:#74c0fc,stroke-width:2px,color:#1864ab
|
||||
style Core fill:#f8f9fa,stroke:#ced4da,stroke-width:2px,color:#495057
|
||||
style Browser fill:#f1f3f5,stroke:#ced4da,stroke-width:2px,color:#495057
|
||||
L_SALES <-->|Native Sync Live and Retry| R_SALES
|
||||
L_INV <-->|Native Sync Live and Retry| R_INV
|
||||
|
||||
%% Styling Nodes
|
||||
style UI fill:#339af0,stroke:#1864ab,color:#fff
|
||||
style REG fill:#1864ab,stroke:#1864ab,color:#fff
|
||||
style INST fill:#339af0,stroke:#1864ab,color:#fff
|
||||
style API fill:#845ef7,stroke:#5f3dc4,color:#fff
|
||||
style FAC fill:#845ef7,stroke:#5f3dc4,color:#fff
|
||||
|
||||
%% Gatekeeper is GREEN (Security Checkpoint), Error is RED
|
||||
style VAL fill:#20c997,stroke:#089981,color:#fff
|
||||
style ERR fill:#fa5252,stroke:#c92a2a,color:#fff
|
||||
|
||||
style LOCAL fill:#845ef7,stroke:#5f3dc4,color:#fff
|
||||
style IDB fill:#845ef7,stroke:#5f3dc4,color:#fff
|
||||
style ENC fill:#fab005,stroke:#e67700,color:#fff
|
||||
style B_LOCAL fill:#868e96,stroke:#495057,color:#fff
|
||||
style B_IDB fill:#868e96,stroke:#495057,color:#fff
|
||||
style MGR fill:#339af0,stroke:#1864ab,color:#fff
|
||||
style L_SALES fill:#845ef7,stroke:#5f3dc4,color:#fff
|
||||
style L_INV fill:#845ef7,stroke:#5f3dc4,color:#fff
|
||||
style R_SALES fill:#fab005,stroke:#e67700,color:#fff
|
||||
style R_INV fill:#fab005,stroke:#e67700,color:#fff
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 🎯 Primary Goals & Architectural Principles
|
||||
## Core Concepts & Usage
|
||||
|
||||
* **App Autonomy (Inversion of Control)**: The core storage engine does not know about your application's keys. Consuming applications define their own keys, their own `encryptedKeys` sets, and their own `plainTextKeys` sets, injecting them into the factory upon instantiation.
|
||||
* **Runtime Gatekeeper (Defensive Programming)**: The engine validates every `setItem`, `getItem`, and `removeItem` operation. If an app attempts to access a key that wasn't explicitly registered in `encryptedKeys` or `plainTextKeys`, the engine will immediately throw a Security Exception to prevent rogue data access/injection.
|
||||
* **Dual Backend Strategy**:
|
||||
* `createLocalStorage`: Ideal for small, synchronous-like data (tokens, user preferences, settings).
|
||||
* `createIndexedDB`: Built for large, asynchronous data (offline drafts, cached API responses, large arrays/blobs) bypassing the 5MB localStorage limit.
|
||||
* **Security by Default**: Developers don't need to manually encrypt/decrypt data. If a key is passed in the `encryptedKeys` configuration, the engine handles AES encryption transparently.
|
||||
* **Corrupt Data Resilience**: If parsing or decryption fails (e.g., tampered data or changed encryption keys), the corrupt entry is safely removed and returns `null`, preventing the app from crashing.
|
||||
### 1. Initialization & Registration (`PouchDatabaseManager`)
|
||||
|
||||
---
|
||||
The `PouchDatabaseManager` acts as the IoC Factory. Apps use it to register and initialize multiple discrete PouchDB databases using a `PouchConfig`.
|
||||
|
||||
## 🚀 App-Level Setup & Usage
|
||||
|
||||
### 1. Define App Keys and Instantiate (Inversion of Control)
|
||||
|
||||
In your consuming application (e.g., `apps/web/src/core/storage/index.ts`), define your keys and use the factories to create your instances.
|
||||
**Why we use this pattern:** Instead of scattering raw database instantiations across the codebase, the manager centralizes connections. If a database is requested twice, the manager efficiently returns the exact same instance.
|
||||
|
||||
```typescript
|
||||
// apps/web/src/core/storage/index.ts
|
||||
import { createLocalStorage, createIndexedDB } from '@repo/core-storage';
|
||||
import { PouchDatabaseManager } from '@repo/core-storage';
|
||||
import type { Item } from './types';
|
||||
|
||||
// 1. Define Keys
|
||||
export const AppStorageKey = {
|
||||
USER_PROFILE: 'user_profile',
|
||||
ACCESS_TOKEN: 'access_token',
|
||||
LOCALE: 'app_locale',
|
||||
} as const;
|
||||
export const dbManager = new PouchDatabaseManager();
|
||||
|
||||
export type AppStorageKeyValue = (typeof AppStorageKey)[keyof typeof AppStorageKey];
|
||||
|
||||
// 2. Classify Keys
|
||||
export const ENCRYPTED_KEYS = new Set<AppStorageKeyValue>([
|
||||
AppStorageKey.USER_PROFILE,
|
||||
AppStorageKey.ACCESS_TOKEN,
|
||||
]);
|
||||
|
||||
export const PLAIN_KEYS = new Set<AppStorageKeyValue>([
|
||||
AppStorageKey.LOCALE,
|
||||
]);
|
||||
|
||||
// 3. Instantiate Factories
|
||||
export const secureStorage = createLocalStorage<AppStorageKeyValue>({
|
||||
encryptedKeys: ENCRYPTED_KEYS,
|
||||
plainTextKeys: PLAIN_KEYS
|
||||
});
|
||||
|
||||
export const secureIndexedDB = createIndexedDB<AppStorageKeyValue>({
|
||||
dbName: 'eigen_erp_db',
|
||||
storeName: 'web_store',
|
||||
encryptedKeys: ENCRYPTED_KEYS,
|
||||
plainTextKeys: PLAIN_KEYS
|
||||
// Register a strictly-typed database with bi-directional sync
|
||||
export const itemDB = dbManager.register<Item>({
|
||||
localName: 'items_db',
|
||||
remoteUrl: 'http://admin:password@localhost:5984/items_db'
|
||||
});
|
||||
```
|
||||
|
||||
### 2. Usage in App Components
|
||||
### 2. CRUD & Queries (`PouchDatabaseWrapper`)
|
||||
|
||||
Now, you can import your locally-created instances anywhere in your app.
|
||||
When you register a database, you receive a strictly typed `PouchDatabaseWrapper`. This wrapper abstracts away the raw PouchDB API, giving developers clean, Promise-based helper methods without ever needing to pass `dbName` or complex identifiers repeatedly.
|
||||
|
||||
| Method | Description |
|
||||
|---|---|
|
||||
| `create(data)` | Inserts a new document. PouchDB will auto-generate an `_id` if omitted. |
|
||||
| `update(id, data)` | Automatically fetches the latest `_rev` to merge the payload, preventing conflict errors. |
|
||||
| `delete(id)` | Automatically fetches the latest `_rev` to safely remove the document. |
|
||||
| `getOne(id)` | Retrieves a single document by its `_id`. |
|
||||
| `getAll()` | Retrieves all documents, automatically filtering out internal `_design/` docs. |
|
||||
| `find(options)` | Queries using MongoDB-style selectors (via `pouchdb-find`). |
|
||||
|
||||
**Example of `find()` with Selectors:**
|
||||
Instead of pulling all documents into memory and filtering them with JavaScript, we leverage native MongoDB-style selectors for performance:
|
||||
|
||||
```typescript
|
||||
import { secureStorage, AppStorageKey } from '@/core/storage';
|
||||
import type { UserProfile } from '@/types';
|
||||
|
||||
// CREATE / UPDATE
|
||||
// Since USER_PROFILE is in ENCRYPTED_KEYS, it is AES-encrypted automatically.
|
||||
await secureStorage.setItem(AppStorageKey.USER_PROFILE, {
|
||||
id: 1,
|
||||
name: 'Firman',
|
||||
role: 'admin'
|
||||
const expensiveItems = await itemDB.find({
|
||||
selector: {
|
||||
price: { $gt: 100 },
|
||||
category: 'electronics'
|
||||
}
|
||||
});
|
||||
```
|
||||
|
||||
// READ (Returns null if not found or if decryption fails)
|
||||
const profile = await secureStorage.getItem<UserProfile>(AppStorageKey.USER_PROFILE);
|
||||
if (profile) {
|
||||
console.log('Welcome back,', profile.name);
|
||||
### 3. Real-Time Reactivity (The `onChange` Pub/Sub Pattern)
|
||||
|
||||
**CRITICAL CONCEPT:** We do **not** expose the raw `db.changes()` feed directly to React components. Instead, the `PouchDatabaseWrapper` utilizes a clean Pub/Sub abstraction via the `.onChange(callback)` method.
|
||||
|
||||
**Why we use this pattern:**
|
||||
1. **Memory Safety:** Direct bindings to PouchDB's raw changes feed often lead to zombie listeners and memory leaks. The `.onChange()` returns an unsubscribe function natively tailored for React's `useEffect` cleanup block.
|
||||
2. **Connection Efficiency:** It maintains a *single* WebSocket/Polling connection to the database under the hood. Multiple React components can subscribe to the same wrapper without opening dozens of parallel database connections.
|
||||
|
||||
```tsx
|
||||
import { useEffect, useCallback, useState } from 'react';
|
||||
import { itemDB } from '../core/db';
|
||||
|
||||
export function InventoryList() {
|
||||
const [items, setItems] = useState([]);
|
||||
|
||||
const loadData = useCallback(async () => {
|
||||
const data = await itemDB.getAll();
|
||||
setItems(data);
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
// 1. Initial Load
|
||||
loadData();
|
||||
|
||||
// 2. Subscribe to local mutations AND remote CouchDB syncs
|
||||
const unsubscribe = itemDB.onChange(() => {
|
||||
console.log('Database updated locally or remotely. Refreshing...');
|
||||
loadData();
|
||||
});
|
||||
|
||||
// 3. Prevent memory leaks!
|
||||
return () => {
|
||||
unsubscribe();
|
||||
};
|
||||
}, [loadData]);
|
||||
|
||||
// UI rendering...
|
||||
}
|
||||
|
||||
// DELETE
|
||||
await secureStorage.removeItem(AppStorageKey.USER_PROFILE);
|
||||
```
|
||||
|
||||
### 3. The Runtime Gatekeeper
|
||||
### 4. CouchDB Sync & CORS Troubleshooting
|
||||
|
||||
If you try to access an unregistered key, the engine protects the app by throwing an error at runtime:
|
||||
By providing a `remoteUrl` to the manager, the engine automatically handles bi-directional synchronization in the background (`live: true, retry: true`). If the server goes down, the local app will continue working seamlessly and sync automatically when the connection is restored.
|
||||
|
||||
```typescript
|
||||
// Throws Error: "[Storage Engine] Security Exception: Key 'rogue_key' is not registered..."
|
||||
await secureStorage.setItem('rogue_key' as any, 'hacked');
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
> [!WARNING]
|
||||
> **Migration Hazard**: If you move an existing key from `plainTextKeys` to `encryptedKeys` (or vice versa), existing users will experience a parsing failure on their next session (because the library expects encrypted data but finds plain text). The resilient parser will catch this and gracefully clear the key, which may effectively log them out or reset their local preference.
|
||||
> [!WARNING]
|
||||
> **CORS Infinite Retries & Preflight Failures**
|
||||
> If your browser blocks the synchronization with a CORS error, you will see PouchDB enter an infinite retry loop in the network tab.
|
||||
>
|
||||
> **Do NOT try to fix this in the frontend code!**
|
||||
> This is exclusively a CouchDB server configuration issue. You must enable CORS directly on the CouchDB instance by editing its `local.ini` or using its dashboard configuration to allow origins, credentials, and headers.
|
||||
@@ -13,12 +13,23 @@
|
||||
"typecheck": "tsc --noEmit"
|
||||
},
|
||||
"dependencies": {
|
||||
"@repo/utils": "workspace:*"
|
||||
"@repo/utils": "workspace:*",
|
||||
"pouchdb-browser": "^9.0.0",
|
||||
"pouchdb-find": "^9.0.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@repo/eslint-config": "workspace:*",
|
||||
"@repo/typescript-config": "workspace:*",
|
||||
"@types/pouchdb": "^6.4.2",
|
||||
"@types/pouchdb-adapter-memory": "^6.1.6",
|
||||
"@types/pouchdb-browser": "^6.1.5",
|
||||
"@types/pouchdb-core": "^7.0.15",
|
||||
"@types/pouchdb-find": "^7.3.3",
|
||||
"@types/pouchdb-mapreduce": "^6.1.10",
|
||||
"eslint": "^8.57.1",
|
||||
"pouchdb-adapter-memory": "^9.0.0",
|
||||
"pouchdb-core": "^9.0.0",
|
||||
"pouchdb-mapreduce": "^9.0.0",
|
||||
"typescript": "5.5.4",
|
||||
"vitest": "^4.0.17"
|
||||
}
|
||||
|
||||
@@ -2,7 +2,9 @@
|
||||
export type { IStorageService } from './storage.interface';
|
||||
export type { StorageOptions } from './local-storage.service';
|
||||
export type { IndexedDBConfig } from './indexed-db.service';
|
||||
export type { PouchConfig } from './pouch';
|
||||
|
||||
// ─── Service Classes ────────────────────────────────────────────
|
||||
export { LocalStorageService, createLocalStorage } from './local-storage.service';
|
||||
export { IndexedDBService, createIndexedDB } from './indexed-db.service';
|
||||
export { PouchDatabaseManager, PouchDatabaseWrapper } from './pouch';
|
||||
|
||||
@@ -0,0 +1,289 @@
|
||||
import PouchDB from 'pouchdb-browser';
|
||||
import PouchDBFind from 'pouchdb-find';
|
||||
|
||||
// Register the find plugin globally
|
||||
PouchDB.plugin(PouchDBFind);
|
||||
|
||||
// ─── Configuration Interface ────────────────────────────────────
|
||||
|
||||
/**
|
||||
* Configuration for creating a new PouchDB database instance.
|
||||
* Follows Inversion of Control — the consuming app decides names and remote URLs.
|
||||
*/
|
||||
export interface PouchConfig {
|
||||
/** Name of the local PouchDB database (stored in IndexedDB by the browser). */
|
||||
localName: string;
|
||||
/**
|
||||
* Optional remote CouchDB URL for bi-directional live sync.
|
||||
* Should include credentials if authentication is required.
|
||||
* Example: `http://user:password@host:port/db_name`
|
||||
*/
|
||||
remoteUrl?: string;
|
||||
}
|
||||
|
||||
// ─── PouchDatabaseWrapper ───────────────────────────────────────
|
||||
|
||||
/**
|
||||
* Object-Oriented wrapper around a single PouchDB instance.
|
||||
* Provides strictly-typed CRUD + query helpers so developers never interact
|
||||
* with the raw PouchDB API or pass `dbName` repeatedly.
|
||||
*
|
||||
* @example
|
||||
* ```typescript
|
||||
* const itemDB = dbManager.register({ localName: 'items' });
|
||||
* await itemDB.create({ _id: 'item-001', name: 'Widget', price: 9.99 });
|
||||
* const results = await itemDB.find({ selector: { price: { $gt: 5 } } });
|
||||
* ```
|
||||
*/
|
||||
export class PouchDatabaseWrapper<DefaultType extends object = any> {
|
||||
/** The underlying raw PouchDB instance (escape hatch for advanced usage). */
|
||||
readonly raw: PouchDB.Database;
|
||||
|
||||
private syncHandler: PouchDB.Replication.Sync<object> | null = null;
|
||||
private listeners = new Set<() => void>();
|
||||
private changesFeed: PouchDB.Core.Changes<object> | null = null;
|
||||
|
||||
constructor(config: PouchConfig) {
|
||||
this.raw = new PouchDB(config.localName);
|
||||
|
||||
// Set up bi-directional live sync if a remote URL is provided
|
||||
if (config.remoteUrl) {
|
||||
this.syncHandler = this.raw.sync(config.remoteUrl, {
|
||||
live: true,
|
||||
retry: true,
|
||||
});
|
||||
|
||||
// Fault-tolerant error handling — prevents app crashes when CouchDB is unreachable
|
||||
this.syncHandler.on('error', (err: unknown) => {
|
||||
console.warn(`[PouchDB Sync] Error on "${config.localName}":`, err);
|
||||
});
|
||||
|
||||
this.syncHandler.on('paused', (info: unknown) => {
|
||||
if (info) {
|
||||
console.warn(`[PouchDB Sync] Paused on "${config.localName}":`, info);
|
||||
}
|
||||
});
|
||||
|
||||
this.syncHandler.on('denied', (err: unknown) => {
|
||||
console.warn(`[PouchDB Sync] Denied on "${config.localName}":`, err);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// ─── CRUD Operations ────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* Create a new document. If `_id` is not provided in data, PouchDB generates one.
|
||||
*/
|
||||
async create<T extends object = DefaultType>(data: T): Promise<PouchDB.Core.Response> {
|
||||
return this.raw.put(data as PouchDB.Core.Document<T>);
|
||||
}
|
||||
|
||||
/**
|
||||
* Update an existing document by ID.
|
||||
* Automatically fetches the latest `_rev` to prevent conflict errors.
|
||||
*/
|
||||
async update<T extends object = DefaultType>(id: string, data: Partial<T>): Promise<PouchDB.Core.Response> {
|
||||
const existing = await this.raw.get(id);
|
||||
const merged = { ...existing, ...data };
|
||||
return this.raw.put(merged);
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete a document by ID.
|
||||
* Automatically fetches the latest `_rev` before removal.
|
||||
*/
|
||||
async delete(id: string): Promise<PouchDB.Core.Response> {
|
||||
const doc = await this.raw.get(id);
|
||||
return this.raw.remove(doc);
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieve a single document by ID.
|
||||
*/
|
||||
async getOne<T = DefaultType>(id: string): Promise<T & PouchDB.Core.IdMeta & PouchDB.Core.RevisionIdMeta> {
|
||||
return this.raw.get<T>(id) as Promise<T & PouchDB.Core.IdMeta & PouchDB.Core.RevisionIdMeta>;
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieve all documents from the database.
|
||||
* Returns a clean array of document objects (excludes PouchDB design docs).
|
||||
*/
|
||||
async getAll<T = DefaultType>(): Promise<T[]> {
|
||||
const result = await this.raw.allDocs({ include_docs: true });
|
||||
return result.rows
|
||||
.filter((row) => !row.id.startsWith('_design/'))
|
||||
.map((row) => row.doc as unknown as T);
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieve multiple documents by their IDs.
|
||||
* Returns a clean array of found documents (silently skips missing/errored entries).
|
||||
*/
|
||||
async getSome<T = DefaultType>(ids: string[]): Promise<T[]> {
|
||||
const result = await this.raw.allDocs({ keys: ids, include_docs: true });
|
||||
return result.rows
|
||||
.filter((row): row is PouchDB.Core.AllDocsResponse<object>['rows'][number] => !('error' in row) && !!(row as any).doc)
|
||||
.map((row) => (row as any).doc as T);
|
||||
}
|
||||
|
||||
/**
|
||||
* Query documents using MongoDB-style selectors (powered by `pouchdb-find`).
|
||||
*
|
||||
* @example
|
||||
* ```typescript
|
||||
* const electronics = await itemDB.find({ selector: { category: 'electronics' } });
|
||||
* const expensive = await itemDB.find({ selector: { price: { $gt: 100 } }, limit: 10 });
|
||||
* ```
|
||||
*/
|
||||
async find<T extends object = DefaultType>(options: PouchDB.Find.FindRequest<T>): Promise<T[]> {
|
||||
const result = await this.raw.find(options as PouchDB.Find.FindRequest<object>);
|
||||
return result.docs as unknown as T[];
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove all documents from the database while keeping the database itself intact.
|
||||
* Useful for "clear cache" or "reset local data" flows.
|
||||
*/
|
||||
async cleanAllData(): Promise<void> {
|
||||
const result = await this.raw.allDocs();
|
||||
const deletions = result.rows
|
||||
.filter((row) => !row.id.startsWith('_design/'))
|
||||
.map((row) => ({
|
||||
_id: row.id,
|
||||
_rev: row.value.rev,
|
||||
_deleted: true as const,
|
||||
}));
|
||||
|
||||
if (deletions.length > 0) {
|
||||
await this.raw.bulkDocs(deletions);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Cancel any active sync and completely destroy the local database.
|
||||
* After calling this, the wrapper instance should not be used again.
|
||||
*/
|
||||
async destroy(): Promise<void> {
|
||||
if (this.syncHandler) {
|
||||
this.syncHandler.cancel();
|
||||
}
|
||||
if (this.changesFeed) {
|
||||
this.changesFeed.cancel();
|
||||
}
|
||||
this.listeners.clear();
|
||||
await this.raw.destroy();
|
||||
}
|
||||
|
||||
/**
|
||||
* Cancel the live sync connection (if active) without destroying the database.
|
||||
*/
|
||||
cancelSync(): void {
|
||||
if (this.syncHandler) {
|
||||
this.syncHandler.cancel();
|
||||
this.syncHandler = null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Subscribe to real-time changes in the database.
|
||||
* Returns an unsubscribe function.
|
||||
*/
|
||||
onChange(callback: () => void): () => void {
|
||||
this.listeners.add(callback);
|
||||
|
||||
if (!this.changesFeed) {
|
||||
this.changesFeed = this.raw.changes({
|
||||
since: 'now',
|
||||
live: true,
|
||||
include_docs: true
|
||||
}).on('change', () => {
|
||||
this.listeners.forEach(cb => cb());
|
||||
}).on('error', (err) => {
|
||||
console.warn(`[PouchDB Listener Error]`, err);
|
||||
});
|
||||
}
|
||||
|
||||
return () => {
|
||||
this.listeners.delete(callback);
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
// ─── PouchDatabaseManager ───────────────────────────────────────
|
||||
|
||||
/**
|
||||
* IoC Factory for managing multiple PouchDB database instances with optional
|
||||
* bi-directional CouchDB synchronization.
|
||||
*
|
||||
* `register()` returns a `PouchDatabaseWrapper` with full CRUD + query helpers,
|
||||
* so developers never need to pass `dbName` into each operation.
|
||||
*
|
||||
* @example
|
||||
* ```typescript
|
||||
* const dbManager = new PouchDatabaseManager();
|
||||
*
|
||||
* const itemDB = dbManager.register({ localName: 'items' });
|
||||
* await itemDB.create({ _id: 'item-001', name: 'Widget', price: 9.99 });
|
||||
*
|
||||
* const results = await itemDB.find({ selector: { price: { $gt: 5 } } });
|
||||
* console.log(results); // [{ _id: 'item-001', name: 'Widget', price: 9.99, ... }]
|
||||
*
|
||||
* const salesDB = dbManager.register({
|
||||
* localName: 'sales',
|
||||
* remoteUrl: 'http://admin:pass@localhost:5984/sales_db',
|
||||
* });
|
||||
* ```
|
||||
*/
|
||||
export class PouchDatabaseManager {
|
||||
private databases = new Map<string, PouchDatabaseWrapper<any>>();
|
||||
|
||||
/**
|
||||
* Register and initialize a new PouchDB database.
|
||||
* If a database with the same `localName` already exists, returns the existing wrapper.
|
||||
*
|
||||
* @param config - Configuration for the database instance.
|
||||
* @returns A `PouchDatabaseWrapper` with CRUD + query helpers.
|
||||
*/
|
||||
register<T extends object = any>(config: PouchConfig): PouchDatabaseWrapper<T> {
|
||||
if (this.databases.has(config.localName)) {
|
||||
return this.databases.get(config.localName) as PouchDatabaseWrapper<T>;
|
||||
}
|
||||
|
||||
const wrapper = new PouchDatabaseWrapper<T>(config);
|
||||
this.databases.set(config.localName, wrapper);
|
||||
return wrapper;
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieve a previously registered database wrapper by its local name.
|
||||
*/
|
||||
get<T extends object = any>(localName: string): PouchDatabaseWrapper<T> | undefined {
|
||||
return this.databases.get(localName) as PouchDatabaseWrapper<T> | undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* Destroy a specific registered database and remove it from the manager.
|
||||
*/
|
||||
async destroy(localName: string): Promise<void> {
|
||||
const wrapper = this.databases.get(localName);
|
||||
if (!wrapper) return;
|
||||
await wrapper.destroy();
|
||||
this.databases.delete(localName);
|
||||
}
|
||||
|
||||
/**
|
||||
* Destroy all managed databases. Useful for logout/cleanup scenarios.
|
||||
*/
|
||||
async destroyAll(): Promise<void> {
|
||||
const names = Array.from(this.databases.keys());
|
||||
await Promise.all(names.map((name) => this.destroy(name)));
|
||||
}
|
||||
|
||||
/**
|
||||
* List all currently registered database names.
|
||||
*/
|
||||
listDatabases(): string[] {
|
||||
return Array.from(this.databases.keys());
|
||||
}
|
||||
}
|
||||
@@ -145,7 +145,7 @@ describe('LocalStorageService', () => {
|
||||
});
|
||||
|
||||
it('returns null for non-existent keys', async () => {
|
||||
const result = await storage.getItem<string>('nonexistent' as TestStorageKeyValue);
|
||||
const result = await storage.getItem<string>(TestStorageKey.THEME);
|
||||
expect(result).toBeNull();
|
||||
});
|
||||
|
||||
|
||||
@@ -0,0 +1,257 @@
|
||||
import { describe, it, expect, beforeEach, afterEach } from 'vitest';
|
||||
import PouchDB from 'pouchdb-core';
|
||||
import PouchDBAdapterMemory from 'pouchdb-adapter-memory';
|
||||
import PouchDBFind from 'pouchdb-find';
|
||||
import PouchDBMapReduce from 'pouchdb-mapreduce';
|
||||
|
||||
// Build a minimal PouchDB for testing: core + memory adapter + find
|
||||
PouchDB.plugin(PouchDBAdapterMemory);
|
||||
PouchDB.plugin(PouchDBFind);
|
||||
PouchDB.plugin(PouchDBMapReduce);
|
||||
|
||||
/**
|
||||
* Since the tests run in Node (not a browser), we cannot use PouchDatabaseManager
|
||||
* directly because it imports `pouchdb-browser` which requires `self`.
|
||||
* Instead, we test the CRUD logic by creating a lightweight test wrapper
|
||||
* that mirrors PouchDatabaseWrapper's methods using the memory-backed PouchDB.
|
||||
*/
|
||||
|
||||
function createTestDB(name: string) {
|
||||
const raw = new PouchDB(name, { adapter: 'memory' });
|
||||
|
||||
return {
|
||||
raw,
|
||||
|
||||
async create<T extends object>(data: T) {
|
||||
return raw.put(data as PouchDB.Core.Document<T>);
|
||||
},
|
||||
|
||||
async update<T extends object>(id: string, data: Partial<T>) {
|
||||
const existing = await raw.get(id);
|
||||
const merged = { ...existing, ...data };
|
||||
return raw.put(merged);
|
||||
},
|
||||
|
||||
async delete(id: string) {
|
||||
const doc = await raw.get(id);
|
||||
return raw.remove(doc);
|
||||
},
|
||||
|
||||
async getOne<T>(id: string) {
|
||||
return raw.get<T>(id) as Promise<T & PouchDB.Core.IdMeta & PouchDB.Core.RevisionIdMeta>;
|
||||
},
|
||||
|
||||
async getAll<T>() {
|
||||
const result = await raw.allDocs({ include_docs: true });
|
||||
return result.rows
|
||||
.filter((row) => !row.id.startsWith('_design/'))
|
||||
.map((row) => row.doc as unknown as T);
|
||||
},
|
||||
|
||||
async getSome<T>(ids: string[]) {
|
||||
const result = await raw.allDocs({ keys: ids, include_docs: true });
|
||||
return result.rows
|
||||
.filter((row): row is any => !('error' in row) && !!(row as any).doc)
|
||||
.map((row: any) => row.doc as T);
|
||||
},
|
||||
|
||||
async find<T extends object>(options: PouchDB.Find.FindRequest<T>) {
|
||||
const result = await raw.find(options as PouchDB.Find.FindRequest<object>);
|
||||
return result.docs as unknown as T[];
|
||||
},
|
||||
|
||||
async cleanAllData() {
|
||||
const result = await raw.allDocs();
|
||||
const deletions = result.rows
|
||||
.filter((row) => !row.id.startsWith('_design/'))
|
||||
.map((row) => ({
|
||||
_id: row.id,
|
||||
_rev: row.value.rev,
|
||||
_deleted: true as const,
|
||||
}));
|
||||
if (deletions.length > 0) {
|
||||
await raw.bulkDocs(deletions);
|
||||
}
|
||||
},
|
||||
|
||||
async destroy() {
|
||||
await raw.destroy();
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
describe('PouchDatabaseWrapper CRUD Operations', () => {
|
||||
let db: ReturnType<typeof createTestDB>;
|
||||
|
||||
beforeEach(() => {
|
||||
// Use a unique name per test to avoid cross-contamination
|
||||
db = createTestDB(`test_db_${Date.now()}_${Math.random().toString(36).slice(2)}`);
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
try {
|
||||
await db.destroy();
|
||||
} catch {
|
||||
// Already destroyed in some tests
|
||||
}
|
||||
});
|
||||
|
||||
// ─── create ───────────────────────────────────────────────────
|
||||
|
||||
describe('create', () => {
|
||||
it('should create a document with a given _id', async () => {
|
||||
const res = await db.create({ _id: 'doc-001', name: 'Alice', age: 30 });
|
||||
expect(res.ok).toBe(true);
|
||||
expect(res.id).toBe('doc-001');
|
||||
});
|
||||
|
||||
it('should throw a conflict if creating with a duplicate _id', async () => {
|
||||
await db.create({ _id: 'dup-001', name: 'First' });
|
||||
await expect(db.create({ _id: 'dup-001', name: 'Second' })).rejects.toThrow();
|
||||
});
|
||||
});
|
||||
|
||||
// ─── getOne ───────────────────────────────────────────────────
|
||||
|
||||
describe('getOne', () => {
|
||||
it('should retrieve a document by id', async () => {
|
||||
await db.create({ _id: 'fetch-001', product: 'Widget', price: 9.99 });
|
||||
|
||||
const doc = await db.getOne<{ product: string; price: number }>('fetch-001');
|
||||
expect(doc._id).toBe('fetch-001');
|
||||
expect(doc.product).toBe('Widget');
|
||||
expect(doc.price).toBe(9.99);
|
||||
});
|
||||
|
||||
it('should throw for a non-existent document', async () => {
|
||||
await expect(db.getOne('non-existent')).rejects.toThrow();
|
||||
});
|
||||
});
|
||||
|
||||
// ─── update ───────────────────────────────────────────────────
|
||||
|
||||
describe('update', () => {
|
||||
it('should merge new fields into an existing document', async () => {
|
||||
await db.create({ _id: 'upd-001', name: 'Original', count: 1 });
|
||||
|
||||
const res = await db.update('upd-001', { count: 42, extra: 'field' });
|
||||
expect(res.ok).toBe(true);
|
||||
|
||||
const updated = await db.getOne<{ name: string; count: number; extra: string }>('upd-001');
|
||||
expect(updated.name).toBe('Original'); // untouched
|
||||
expect(updated.count).toBe(42); // updated
|
||||
expect(updated.extra).toBe('field'); // newly added
|
||||
});
|
||||
|
||||
it('should throw when updating a non-existent document', async () => {
|
||||
await expect(db.update('ghost', { name: 'nope' })).rejects.toThrow();
|
||||
});
|
||||
});
|
||||
|
||||
// ─── delete ───────────────────────────────────────────────────
|
||||
|
||||
describe('delete', () => {
|
||||
it('should remove a document by id', async () => {
|
||||
await db.create({ _id: 'del-001', name: 'ToBeDeleted' });
|
||||
|
||||
const res = await db.delete('del-001');
|
||||
expect(res.ok).toBe(true);
|
||||
|
||||
await expect(db.getOne('del-001')).rejects.toThrow();
|
||||
});
|
||||
});
|
||||
|
||||
// ─── getAll ───────────────────────────────────────────────────
|
||||
|
||||
describe('getAll', () => {
|
||||
it('should return all documents as a flat array', async () => {
|
||||
await db.create({ _id: 'a', val: 1 });
|
||||
await db.create({ _id: 'b', val: 2 });
|
||||
await db.create({ _id: 'c', val: 3 });
|
||||
|
||||
const all = await db.getAll<{ val: number }>();
|
||||
expect(all).toHaveLength(3);
|
||||
expect(all.map((d: any) => d.val).sort()).toEqual([1, 2, 3]);
|
||||
});
|
||||
|
||||
it('should return empty array for empty database', async () => {
|
||||
const all = await db.getAll();
|
||||
expect(all).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
// ─── getSome ──────────────────────────────────────────────────
|
||||
|
||||
describe('getSome', () => {
|
||||
it('should return only the requested documents', async () => {
|
||||
await db.create({ _id: 'x1', v: 10 });
|
||||
await db.create({ _id: 'x2', v: 20 });
|
||||
await db.create({ _id: 'x3', v: 30 });
|
||||
|
||||
const some = await db.getSome<{ v: number }>(['x1', 'x3']);
|
||||
expect(some).toHaveLength(2);
|
||||
expect(some.map((d: any) => d.v).sort()).toEqual([10, 30]);
|
||||
});
|
||||
|
||||
it('should silently skip missing ids', async () => {
|
||||
await db.create({ _id: 'exists', v: 1 });
|
||||
|
||||
const some = await db.getSome<{ v: number }>(['exists', 'ghost']);
|
||||
expect(some).toHaveLength(1);
|
||||
expect((some[0] as any).v).toBe(1);
|
||||
});
|
||||
});
|
||||
|
||||
// ─── find (pouchdb-find selectors) ────────────────────────────
|
||||
|
||||
describe('find', () => {
|
||||
it('should filter documents using selectors', async () => {
|
||||
await db.create({ _id: 'p1', category: 'electronics', price: 100 });
|
||||
await db.create({ _id: 'p2', category: 'clothing', price: 50 });
|
||||
await db.create({ _id: 'p3', category: 'electronics', price: 200 });
|
||||
|
||||
const results = await db.find<{ category: string; price: number }>({
|
||||
selector: { category: 'electronics' },
|
||||
});
|
||||
|
||||
expect(results).toHaveLength(2);
|
||||
expect(results.every((r) => r.category === 'electronics')).toBe(true);
|
||||
});
|
||||
|
||||
it('should support $gt comparisons', async () => {
|
||||
await db.create({ _id: 'i1', price: 10 });
|
||||
await db.create({ _id: 'i2', price: 50 });
|
||||
await db.create({ _id: 'i3', price: 100 });
|
||||
|
||||
const results = await db.find<{ price: number }>({
|
||||
selector: { price: { $gt: 40 } },
|
||||
});
|
||||
|
||||
expect(results).toHaveLength(2);
|
||||
expect(results.every((r) => r.price > 40)).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
// ─── cleanAllData ─────────────────────────────────────────────
|
||||
|
||||
describe('cleanAllData', () => {
|
||||
it('should remove all documents but keep the database intact', async () => {
|
||||
await db.create({ _id: 'c1', name: 'One' });
|
||||
await db.create({ _id: 'c2', name: 'Two' });
|
||||
await db.create({ _id: 'c3', name: 'Three' });
|
||||
|
||||
let all = await db.getAll();
|
||||
expect(all).toHaveLength(3);
|
||||
|
||||
await db.cleanAllData();
|
||||
|
||||
all = await db.getAll();
|
||||
expect(all).toHaveLength(0);
|
||||
|
||||
// Database should still be functional after cleaning
|
||||
await db.create({ _id: 'c4', name: 'Four' });
|
||||
all = await db.getAll();
|
||||
expect(all).toHaveLength(1);
|
||||
});
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user