### Initialize and use JSONDatabase in JavaScript Source: https://github.com/sethunthunder111/jsondb-high/blob/main/docs/docs.html A quick start example demonstrating how to initialize a JSONDatabase instance and perform basic 'set' and 'get' operations. This showcases the asynchronous nature of database interactions. ```javascript import JSONDatabase from 'jsondb-high'; const db = new JSONDatabase('db.json'); // Write await db.set('user.1', { name: 'Alice', role: 'admin' }); // Read const user = await db.get('user.1'); console.log(user); // { name: 'Alice', role: 'admin' } ``` -------------------------------- ### Install jsondb-high using npm or bun Source: https://github.com/sethunthunder111/jsondb-high/blob/main/docs/docs.html Instructions for installing the jsondb-high package using either bun or npm. This package requires Rust and Cargo for its native core build. ```bash # Using bun (recommended) bun add jsondb-high # Using npm npm install jsondb-high ``` -------------------------------- ### Install jsondb-high using npm or bun Source: https://github.com/sethunthunder111/jsondb-high/blob/main/README.md This snippet shows how to install the jsondb-high package using either bun or npm. The installation process includes building the native Rust core from source, requiring Rust and Cargo to be installed. ```bash bun add jsondb-high # or npm install jsondb-high ``` -------------------------------- ### Configure O(1) Indexing for JSONDatabase Source: https://github.com/sethunthunder111/jsondb-high/blob/main/docs/docs.html Example of setting up O(1) indexing for faster lookups. This configuration specifies an index named 'email' on the 'users' collection, targeting the 'email' field. ```javascript const db = new JSONDatabase('db.json', { indices: [{ name: 'email', path: 'users', field: 'email' }] }); // Instant Lookup const user = await db.findByIndex('email', 'alice@corp.com'); ``` -------------------------------- ### Perform Basic Database Operations (Set, Get, Has, Delete) Source: https://github.com/sethunthunder111/jsondb-high/blob/main/docs/docs.html Illustrates fundamental database operations: setting a value, getting a value with a default, checking for a key's existence, and deleting a nested property. ```javascript await db.set('config.theme', 'dark'); const val = await db.get('config.theme', 'light'); if (await db.has('users.1')) { ... } await db.delete('users.1.settings'); ``` -------------------------------- ### Initialize and use jsondb-high in Node.js Source: https://github.com/sethunthunder111/jsondb-high/blob/main/README.md A quick start example demonstrating how to initialize a jsondb-high database instance, set a key-value pair, and retrieve the value. The database file is automatically created if it doesn't exist. ```typescript import JSONDatabase from 'jsondb-high'; // Initialize (Auto-creates file if missing) const db = new JSONDatabase('db.json'); // Write await db.set('user.1', { name: 'Alice', role: 'admin' }); // Read const user = await db.get('user.1'); console.log(user); // { name: 'Alice', role: 'admin' } ``` -------------------------------- ### Use the Query Builder for Complex Queries Source: https://github.com/sethunthunder111/jsondb-high/blob/main/docs/docs.html An example of using the query builder to construct and execute complex queries. This demonstrates filtering data with 'where', limiting results, sorting, and selecting specific fields. ```javascript const results = await db.query('users') .where('age').gt(18) .where('role').eq('admin') .limit(10) .sort({ age: -1 }) .select(['id', 'name']) .exec(); ``` -------------------------------- ### Configure Durability Modes for JSONDatabase Source: https://github.com/sethunthunder111/jsondb-high/blob/main/docs/docs.html Example of configuring different durability modes ('none', 'lazy', 'batched', 'sync') and WAL flush intervals for the JSONDatabase. The 'batched' mode with a 10ms flush interval is recommended for a balance of throughput and durability. ```javascript const db = new JSONDatabase('db.json', { durability: 'batched', // 'none' | 'lazy' | 'batched' | 'sync' walFlushMs: 10, // Sync every 10ms (Group Commit) lockMode: 'exclusive' }); ``` -------------------------------- ### Utilize Utility Methods for Data Management Source: https://github.com/sethunthunder111/jsondb-high/blob/main/docs/docs.html Perform common data management tasks such as retrieving keys, values, counts, clearing the database, getting statistics, forcing a save, or performing a durability sync. ```javascript await db.keys('users'); await db.values('users'); await db.count('users'); await db.clear(); await db.stats(); await db.save(); // Force save await db.sync(); // Durability sync ``` -------------------------------- ### Retrieve Data with get() in TypeScript Source: https://github.com/sethunthunder111/jsondb-high/blob/main/README.md The `get` operation retrieves data from a specified path. If the path does not exist, it returns the provided `defaultValue`. This is useful for accessing configuration or user data safely. ```typescript const val = await db.get('config.theme', 'light'); ``` -------------------------------- ### Utility Methods for JSONDatabase Operations Source: https://context7.com/sethunthunder111/jsondb-high/llms.txt Demonstrates common utility operations for JSONDatabase, including setting data, retrieving keys and values, counting items, getting database statistics, saving, syncing, checking WAL status, clearing data, and closing the database. ```typescript const db = new JSONDatabase('db.json'); await db.set('users', { 'alice': { name: 'Alice', role: 'admin' }, 'bob': { name: 'Bob', role: 'user' }, 'charlie': { name: 'Charlie', role: 'user' } }); // Get all keys under a path const userKeys = await db.keys('users'); console.log('User keys:', userKeys); // Output: User keys: ['alice', 'bob', 'charlie'] // Get all values under a path const users = await db.values('users'); console.log('User count:', users.length); // Output: User count: 3 // Count items const userCount = await db.count('users'); console.log('Total users:', userCount); // Output: Total users: 3 // Get database statistics const stats = await db.stats(); console.log('DB Stats:', stats); // Output: { size: 1234, keys: 3, indices: 0, ttlKeys: 0, subscriptions: 0 } // Force save to disk await db.save(); // Explicit durability sync (for WAL mode) await db.sync(); // Check WAL status const walStatus = db.walStatus(); console.log('WAL Status:', walStatus); // Output: { enabled: true, committedLsn: 12345 } // Clear all data await db.clear(); const afterClear = await db.get(''); console.log('After clear:', afterClear); // Output: After clear: {} // Clean shutdown (releases locks, flushes WAL) await db.close(); ``` -------------------------------- ### Get System Information for Parallel Processing in TypeScript Source: https://github.com/sethunthunder111/jsondb-high/blob/main/README.md The `getSystemInfo` method provides details about the system's capabilities for parallel processing, including available cores and whether parallel processing is enabled. ```typescript const info = db.getSystemInfo(); console.log(info); // { // availableCores: 8, // parallelEnabled: true, // recommendedBatchSize: 1000 // } ``` -------------------------------- ### Create and Restore Snapshots Source: https://github.com/sethunthunder111/jsondb-high/blob/main/docs/docs.html Generate a backup of the database using `createSnapshot` and restore it later with `restoreSnapshot`. Snapshots are useful for data backup and recovery. ```javascript const backupPath = await db.createSnapshot('daily'); await db.restoreSnapshot(backupPath); ``` -------------------------------- ### Database Snapshots with jsondb-high Source: https://context7.com/sethunthunder111/jsondb-high/llms.txt Illustrates how to create and restore database backups using the snapshot feature. This includes creating named snapshots, making changes to the database, and then restoring it to a previous state. Event listeners for snapshot creation and restoration are also shown. ```typescript const db = new JSONDatabase('db.json'); // Setup some data await db.set('users', { '1': { name: 'Alice', email: 'alice@example.com' }, '2': { name: 'Bob', email: 'bob@example.com' } }); await db.set('config', { version: '1.0', theme: 'dark' }); // Create snapshot with name const backupPath = await db.createSnapshot('daily'); console.log('Backup saved to:', backupPath); // Output: Backup saved to: db.json.daily.2024-01-15T10-30-00-000Z.bak // Create another snapshot const beforeMigration = await db.createSnapshot('pre-migration'); // Make changes await db.delete('users.1'); await db.set('config.version', '2.0'); console.log('After changes:', await db.get('users')); // Output: After changes: { '2': { name: 'Bob', email: 'bob@example.com' } } // Restore from snapshot await db.restoreSnapshot(beforeMigration); console.log('After restore:', await db.get('users')); // Output: After restore: { '1': {...}, '2': {...} } console.log('Config version:', (await db.get('config') as any).version); // Output: Config version: 1.0 // Listen for snapshot events db.on('snapshot:created', ({ path, name }) => { console.log(`Snapshot '${name}' created at ${path}`); }); db.on('snapshot:restored', ({ path }) => { console.log(`Restored from ${path}`); }); ``` -------------------------------- ### Initialize JSONDatabase with Options Source: https://context7.com/sethunthunder111/jsondb-high/llms.txt Initializes a new JSONDatabase instance with various configuration options. This includes settings for durability, memory management, indexing, schema validation, security, and performance tuning. The database file is auto-created if it doesn't exist. ```typescript import JSONDatabase from 'jsondb-high'; // Simple initialization (auto-creates file if missing) const db = new JSONDatabase('db.json'); // Full configuration with all options const dbConfigured = new JSONDatabase('db.json', { // Durability & Safety lockMode: 'exclusive', // 'exclusive' | 'shared' | 'none' durability: 'batched', // 'none' | 'lazy' | 'batched' | 'sync' walFlushMs: 10, // Sync every 10ms (Group Commit) walBatchSize: 1000, // Memory Management memoryLimit: '512mb', // Max memory usage coldStorageDir: './cold', // LRU eviction storage evictionThresholdPct: 80, // Start evicting at 80% usage evictionTargetPct: 60, // Indexing indices: [ { name: 'email', path: 'users', field: 'email' } ], // Schema Validation schemas: { 'users': { type: 'object', properties: { id: { type: 'number' }, email: { type: 'string', pattern: '^[\w.-]+@[\w.-]+\.\w+$' } }, required: ['id', 'email'] } }, // Security encryptionKey: 'your-32-character-secret-key!!', // Performance slowQueryThresholdMs: 100 }); // Clean shutdown await db.close(); ``` -------------------------------- ### Get Data from JSONDatabase Source: https://context7.com/sethunthunder111/jsondb-high/llms.txt Retrieves data from a specified path in the JSONDatabase. If the path does not exist, it returns an optional default value. Supports typed retrieval for objects and a synchronous get method for performance-critical operations. ```typescript const db = new JSONDatabase('db.json'); // Get simple value const theme = await db.get('config.theme'); // Returns: 'dark' // Get with default value const language = await db.get('config.language', 'en'); // Returns: 'en' if path doesn't exist // Get object const user = await db.get<{ name: string; role: string }>('user.1'); // Returns: { name: 'Alice', role: 'admin', settings: { notifications: true } } // Get nested value const notifications = await db.get('users.1.settings.notifications'); // Returns: false // Synchronous get (for performance-critical paths) const syncValue = db.getSync('config.theme', 'light'); ``` -------------------------------- ### Basic Operations Source: https://github.com/sethunthunder111/jsondb-high/blob/main/README.md Provides methods for setting, getting, checking existence, and deleting data within the JSON database. Paths are automatically created as needed. ```APIDOC ## Basic Operations ### `set(path, value)` Writes data to the specified path. Creates nested paths automatically if they do not exist. ### Method `set` ### Parameters #### Path Parameters - **path** (string) - Required - The path to the data to be written. - **value** (any) - Required - The data to be written at the specified path. ### Request Example ```typescript await db.set('config.theme', 'dark'); await db.set('users.1.settings.notifications', true); ``` ### `get(path, defaultValue?) Retrieves data from the specified path. Returns `defaultValue` if the path does not exist. ### Method `get` ### Parameters #### Path Parameters - **path** (string) - Required - The path to the data to retrieve. - **defaultValue** (any) - Optional - The value to return if the path does not exist. ### Request Example ```typescript const val = await db.get('config.theme', 'light'); ``` ### `has(path)` Checks if a key or path exists in the database. ### Method `has` ### Parameters #### Path Parameters - **path** (string) - Required - The path to check for existence. ### Request Example ```typescript if (await db.has('users.1')) { // User exists } ``` ### `delete(path)` Removes a key or object property from the database. Can remove nested properties or entire objects. ### Method `delete` ### Parameters #### Path Parameters - **path** (string) - Required - The path to the data to delete. ### Request Example ```typescript await db.delete('users.1.settings'); // Delete nested property await db.delete('users.1'); // Delete entire object ``` ``` -------------------------------- ### Snapshots Source: https://github.com/sethunthunder111/jsondb-high/blob/main/docs/docs.html Create and restore database snapshots for backup and recovery purposes. ```APIDOC ## Snapshots ### Description Create and restore database snapshots for backup and recovery purposes. ### Method `createSnapshot`, `restoreSnapshot` ### Endpoint N/A (File system operations) ### Parameters - `name` (string, optional) - A name for the snapshot (e.g., 'daily', 'weekly'). Defaults to a timestamp if not provided. - `path` (string) - The path to the snapshot file for `restoreSnapshot`. ### Request Example ```javascript // Create a snapshot named 'daily' const backupPath = await db.createSnapshot('daily'); // Restore a snapshot from a specific path await db.restoreSnapshot(backupPath); ``` ### Response #### Success Response (200) - `createSnapshot` returns the path to the created snapshot file (string). - `restoreSnapshot` returns nothing upon successful restoration. #### Response Example ```json // Example for createSnapshot: "./snapshots/2023-10-27T10:00:00Z.json" ``` ``` -------------------------------- ### Build and Test jsondb-high with Bun Source: https://github.com/sethunthunder111/jsondb-high/blob/main/README.md Commands for building the native module, running tests, executing benchmarks, and building a debug version of the jsondb-high project using Bun. ```bash # Build native module bun run build # Run tests bun test # Run benchmarks bun run bench # Build debug version bun run build:debug ``` -------------------------------- ### Manage Time-to-Live (TTL) for Keys in TypeScript Source: https://github.com/sethunthunder111/jsondb-high/blob/main/README.md Implement automatic key expiration similar to Redis. This feature allows setting, getting, clearing, and checking the TTL for database keys. ```typescript // Set with TTL (expires in 60 seconds) await db.setWithTTL('session.abc123', { userId: 1 }, 60); // Set TTL on existing key db.setTTL('temp.data', 300); // Get remaining TTL (-1 = no TTL, -2 = key doesn't exist) const ttl = await db.getTTL('session.abc123'); // Remove TTL (make persistent) db.clearTTL('session.abc123'); // Check if key has TTL if (db.hasTTL('session.abc123')) { ... } // Listen for expirations db.on('ttl:expired', ({ path }) => { console.log('Key expired:', path); }); ``` -------------------------------- ### Manual Offload and Restore of Collections Source: https://github.com/sethunthunder111/jsondb-high/blob/main/README.md Provides methods to manually offload a collection to disk to free up memory and to restore it. Data is also transparently restored on access via the `get` method. ```typescript // Offload a collection to disk to free memory const id = await db.offload('largeCollection'); // Data is automatically restored on access: const data = await db.get('largeCollection.key1'); // Transparent restore // Or manually restore: await db.restore('largeCollection'); ``` -------------------------------- ### Memory Management with Cold Storage in jsondb-high Source: https://context7.com/sethunthunder111/jsondb-high/llms.txt Explains how to configure and utilize jsondb-high's memory management features, including setting memory limits, defining a cold storage directory, and configuring eviction thresholds. It demonstrates offloading data, automatic restoration on access, manual restoration, and triggering eviction checks. ```typescript const db = new JSONDatabase('db.json', { memoryLimit: '256mb', // Max memory usage coldStorageDir: './cold', // Where evicted data is stored evictionThresholdPct: 80, // Start evicting at 80% usage evictionTargetPct: 60 // Evict until 60% usage }); // Add large datasets for (let i = 0; i < 100; i++) { await db.set(`largeCollection.${i}`, { data: 'x'.repeat(10000), // 10KB per entry metadata: { id: i, timestamp: Date.now() } }); } // Check memory stats const stats = await db.memoryStats(); console.log('Memory Stats:', stats); // Output: { // totalEstimatedBytes: 1048576, // maxMemoryBytes: 268435456, // coldKeysCount: 0, // hotKeysCount: 100, // utilizationPct: 0.4 // } // Manually offload a collection to free memory const offloadId = await db.offload('largeCollection'); console.log('Offloaded with ID:', offloadId); // Data is automatically restored on access (transparent) const item = await db.get('largeCollection.50'); console.log('Item restored:', item.metadata.id); // Output: Item restored: 50 // Or manually restore await db.restore('largeCollection'); // Trigger eviction check manually const evictedKeys = await db.checkMemoryPressure(); console.log('Evicted keys:', evictedKeys); ``` -------------------------------- ### Initialize Encrypted Database Source: https://github.com/sethunthunder111/jsondb-high/blob/main/docs/docs.html Create a new JSONDatabase instance with encryption enabled. A 32-character secret key is required for encryption and decryption. ```javascript const db = new JSONDatabase('secure.json', { encryptionKey: 'your-32-character-secret-key!!' }); ``` -------------------------------- ### Encryption Source: https://github.com/sethunthunder111/jsondb-high/blob/main/docs/docs.html Initialize the database with an encryption key to encrypt and decrypt data at rest. ```APIDOC ## Encryption ### Description Initialize the database with an encryption key to encrypt and decrypt data at rest. ### Method `JSONDatabase` constructor ### Endpoint N/A (Configuration option) ### Parameters - `filePath` (string) - The path to the database file. - `options` (object) - `encryptionKey` (string) - A 32-character secret key for AES-256 encryption. ### Request Example ```javascript const db = new JSONDatabase('secure.json', { encryptionKey: 'your-32-character-secret-key!!' }); ``` ### Response #### Success Response (200) - A new `JSONDatabase` instance configured with encryption. #### Response Example N/A ``` -------------------------------- ### Configure jsondb-high locking modes Source: https://github.com/sethunthunder111/jsondb-high/blob/main/README.md This example shows how to configure the lock mode for jsondb-high to prevent data corruption when multiple processes access the same file. Available modes are 'exclusive', 'shared', and 'none'. ```typescript const db = new JSONDatabase('db.json', { lockMode: 'exclusive' // 'exclusive' | 'shared' | 'none' }); ``` -------------------------------- ### Perform Array Operations (Push, Pull) Source: https://github.com/sethunthunder111/jsondb-high/blob/main/docs/docs.html Demonstrates how to manipulate array data within the database. 'push' adds elements to an array, while 'pull' removes specified elements. ```javascript await db.push('users.1.tags', 'premium', 'beta'); await db.pull('users.1.tags', 'beta'); ``` -------------------------------- ### Implement schema validation in jsondb-high Source: https://github.com/sethunthunder111/jsondb-high/blob/main/README.md This snippet illustrates how to define and use JSON schemas with jsondb-high to enforce data structure and validation rules. It shows examples of valid and invalid data entries that trigger validation errors. ```typescript const db = new JSONDatabase('db.json', { schemas: { 'users': { type: 'object', properties: { id: { type: 'number' }, email: { type: 'string', pattern: '^[w.-]+@[w.-]+.w+$' }, age: { type: 'number', minimum: 0, maximum: 150 }, role: { type: 'string', enum: ['admin', 'user', 'guest'] }, tags: { type: 'array', items: { type: 'string' }, uniqueItems: true } }, required: ['id', 'email'] } } }); // This will throw validation error (missing required field) await db.set('users.1', { id: 1 }); // ❌ Error: Missing required property: email // This will throw validation error (invalid email pattern) await db.set('users.1', { id: 1, email: 'invalid-email' }); // ❌ Error: String does not match pattern // Valid data await db.set('users.1', { id: 1, email: 'alice@example.com', age: 25, role: 'admin', tags: ['premium', 'beta'] }); // ✅ Success ``` -------------------------------- ### Utility Methods Source: https://github.com/sethunthunder111/jsondb-high/blob/main/docs/docs.html Provides various utility functions for managing and inspecting the database. ```APIDOC ## Utility Methods ### Description Provides various utility functions for managing and inspecting the database. ### Method `keys`, `values`, `count`, `clear`, `stats`, `save`, `sync` ### Endpoint N/A (In-memory and file system operations) ### Parameters - `path` (string, optional) - The path to operate on. If omitted, it often applies to the entire database. ### Request Example ```javascript // Get all keys in the 'users' collection const userKeys = await db.keys('users'); // Get all values in the 'users' collection const userValues = await db.values('users'); // Count documents in the 'users' collection const userCount = await db.count('users'); // Clear the entire database await db.clear(); // Get database statistics const statistics = await db.stats(); // Force save the database to disk await db.save(); // Force sync the database for durability await db.sync(); ``` ### Response #### Success Response (200) - `keys` returns an array of keys (strings). - `values` returns an array of values. - `count` returns the number of documents (number). - `clear` returns nothing. - `stats` returns an object with database statistics. - `save` returns nothing. - `sync` returns nothing. #### Response Example ```json // Example for keys('users'): ["1", "2", "3"] // Example for values('users'): [ { "id": 1, "name": "Alice" }, { "id": 2, "name": "Bob" } ] // Example for count('users'): 3 // Example for stats(): { "totalKeys": 1000, "totalSize": "10MB", "lastSaved": "2023-10-27T10:00:00Z" } ``` ``` -------------------------------- ### TypeScript Interface for DBOptions Source: https://github.com/sethunthunder111/jsondb-high/blob/main/docs/docs.html Defines the configuration options for initializing or configuring the jsondb-high database. Includes settings for indexing, write-ahead logging, encryption, auto-save, locking, durability, and schema definitions. ```typescript interface DBOptions { indices?: IndexConfig[]; wal?: boolean; encryptionKey?: string; autoSaveInterval?: number; lockMode?: 'exclusive' | 'shared' | 'none'; lockTimeoutMs?: number; durability?: 'none' | 'lazy' | 'batched' | 'sync'; walBatchSize?: number; walFlushMs?: number; schemas?: Record; slowQueryThresholdMs?: number; } interface IndexConfig { name: string; path: string; field: string; } ``` -------------------------------- ### Pub/Sub Source: https://github.com/sethunthunder111/jsondb-high/blob/main/docs/docs.html Subscribe to changes in specific paths and receive real-time updates. ```APIDOC ## Pub/Sub ### Description Subscribe to changes in specific paths and receive real-time updates. ### Method `subscribe`, `unsubscribe` ### Endpoint N/A (In-memory operations) ### Parameters - `path` (string) - The path to subscribe to (supports wildcards like `users.*`). - `callback` (function) - A function to be called when changes occur. It receives the new value as an argument. ### Request Example ```javascript // Subscribe to changes in any path under 'users.*' const unsubscribe = db.subscribe('users.*', (newVal) => { console.log('Changed:', newVal); }); // To stop listening: unsubscribe(); ``` ### Response #### Success Response (200) - `subscribe` returns an `unsubscribe` function that can be called to stop listening. #### Response Example N/A ``` -------------------------------- ### TTL (Time to Live) Source: https://github.com/sethunthunder111/jsondb-high/blob/main/docs/docs.html Set a time-to-live for specific keys, after which they will be automatically deleted. ```APIDOC ## TTL (Time to Live) ### Description Set a time-to-live for specific keys, after which they will be automatically deleted. ### Method `setWithTTL` ### Endpoint N/A (In-memory operations) ### Parameters - `path` (string) - The path to the key. - `value` (any) - The value to store. - `ttlSeconds` (number) - The time-to-live in seconds. ### Request Example ```javascript // Set a session key with a TTL of 60 seconds await db.setWithTTL('session.abc', { id: 1 }, 60); ``` ### Response #### Success Response (200) - No explicit return value, operation is performed asynchronously. #### Response Example N/A ``` -------------------------------- ### Configure Locking Modes for JSONDatabase Source: https://github.com/sethunthunder111/jsondb-high/blob/main/docs/docs.html Demonstrates how to set the 'lockMode' option ('exclusive', 'shared', 'none') when initializing JSONDatabase to prevent data corruption when multiple processes access the same database file. ```javascript const db = new JSONDatabase('db.json', { lockMode: 'exclusive' // 'exclusive' | 'shared' | 'none' }); ``` -------------------------------- ### Events Source: https://github.com/sethunthunder111/jsondb-high/blob/main/docs/docs.html Listen for various database events to react to changes and lifecycle moments. ```APIDOC ## Events ### Description Listen for various database events to react to changes and lifecycle moments. ### Method `on` ### Endpoint N/A (Event listeners) ### Parameters - `eventName` (string) - The name of the event to listen for (e.g., 'change', 'error'). - `listener` (function) - The callback function to execute when the event is emitted. ### Request Example ```javascript db.on('change', ({ path, value, oldValue }) => { console.log(`Change detected at path: ${path}`); }); db.on('error', (error) => { console.error('Database error:', error); }); db.on('transaction:commit', () => { console.log('Transaction committed.'); }); db.on('snapshot:created', ({ path, name }) => { console.log(`Snapshot created: ${name} at ${path}`); }); ``` ### Response #### Success Response (200) - Event listeners are registered. No direct return value. #### Response Example N/A ``` -------------------------------- ### Implement Client-Side Search in JavaScript Source: https://github.com/sethunthunder111/jsondb-high/blob/main/docs/docs.html This JavaScript code enables client-side search functionality for a webpage. It indexes headings, listens for input events on a search bar, and displays matching results. It also includes keyboard shortcuts for focus and logic to close the search results when clicking outside the search area. Dependencies include HTML elements with specific IDs like 'searchInput' and 'searchResults', and elements with classes '.docs-content h2, .docs-content h3'. ```javascript const searchInput = document.getElementById('searchInput'); const searchResults = document.getElementById('searchResults'); if (searchInput) { const searchIndex = []; document.querySelectorAll('.docs-content h2, .docs-content h3').forEach(el => { if (el.id) { searchIndex.push({ text: el.textContent.toLowerCase(), title: el.textContent, id: el.id }); } }); searchInput.addEventListener('input', (e) => { const query = e.target.value.toLowerCase(); if (!query) { searchResults.style.display = 'none'; return; } const results = searchIndex.filter(item => item.text.includes(query)).slice(0, 5); if (results.length > 0) { searchResults.innerHTML = results.map(r => ( `
${r.title}
` )).join(''); searchResults.style.display = 'block'; } else { searchResults.style.display = 'none'; } }); // CMD+K document.addEventListener('keydown', (e) => { if ((e.metaKey || e.ctrlKey) && e.key === 'k') { e.preventDefault(); searchInput.focus(); } }); // Close search on click outside document.addEventListener('click', (e) => { if (!searchInput.contains(e.target) && !searchResults.contains(e.target)) { searchResults.style.display = 'none'; } }); } ``` -------------------------------- ### Initialize and Set Data in JSONDatabase (JavaScript) Source: https://github.com/sethunthunder111/jsondb-high/blob/main/docs/index.html Demonstrates basic usage of JSONDatabase by initializing an instance and setting a key-value pair. This is a fundamental operation for interacting with the database. ```javascript let db = new JSONDatabase(); await db.set('speed', 'infinite'); ``` -------------------------------- ### Pagination Source: https://github.com/sethunthunder111/jsondb-high/blob/main/docs/docs.html Paginate through collections to retrieve data in chunks. ```APIDOC ## Pagination ### Description Paginate through collections to retrieve data in chunks. ### Method `paginate` ### Endpoint N/A (In-memory operations) ### Parameters - `collection` (string) - The name of the collection to paginate. - `pageNumber` (number) - The desired page number (1-based). - `pageSize` (number) - The number of documents per page. ### Request Example ```javascript // Get the first page of users with 20 documents per page const page = await db.paginate('users', 1, 20); ``` ### Response #### Success Response (200) - `page` (object) - An object containing pagination details and the data for the current page. - `data` (array) - The documents for the current page. - `currentPage` (number) - The current page number. - `pageSize` (number) - The number of documents per page. - `totalPages` (number) - The total number of pages. - `totalDocuments` (number) - The total number of documents in the collection. #### Response Example ```json { "data": [ { "id": 1, "name": "Alice" }, { "id": 2, "name": "Bob" } ], "currentPage": 1, "pageSize": 20, "totalPages": 5, "totalDocuments": 100 } ``` ``` -------------------------------- ### Implement Middleware for Data Operations Source: https://github.com/sethunthunder111/jsondb-high/blob/main/docs/docs.html Define middleware functions that execute before or after specific database operations. This allows for custom logic, such as automatically updating timestamps. ```javascript db.before('set', 'users.*', (ctx) => { ctx.value.updatedAt = Date.now(); return ctx; }); ``` -------------------------------- ### Populate Footer Navigation in JavaScript Source: https://github.com/sethunthunder111/jsondb-high/blob/main/docs/docs.html This JavaScript code populates a footer navigation element with 'Previous' and 'Next' links. It targets an HTML element with the ID 'docsFooterNav' and dynamically inserts anchor tags for navigation, likely to a home page and a benchmarks page based on the provided HTML structure. It requires an element with the ID 'docsFooterNav' to exist in the HTML. ```javascript // Populate Footer Navigation const footerNav = document.getElementById('docsFooterNav'); if (footerNav) { footerNav.innerHTML = ` Previous Home Next Benchmarks `; } ``` -------------------------------- ### Perform Math Operations (Add, Subtract) Source: https://github.com/sethunthunder111/jsondb-high/blob/main/docs/docs.html Shows how to perform atomic increment and decrement operations on numeric values stored in the database. These operations are useful for counters or managing numerical data. ```javascript const newCount = await db.add('users.1.loginCount', 1); const newCredits = await db.subtract('users.1.credits', 50); ``` -------------------------------- ### Batch Set Data in Parallel with TypeScript Source: https://context7.com/sethunthunder111/jsondb-high/llms.txt Efficiently sets multiple key-value pairs in the database concurrently using all available CPU cores. This method is optimized for large batches and automatically scales with system capabilities. It requires an array of operations, each with a 'path' and 'value'. ```typescript const db = new JSONDatabase('db.json'); // Check system capabilities const sysInfo = db.getSystemInfo(); console.log('System Info:', sysInfo); // Output: { availableCores: 8, parallelEnabled: true, recommendedBatchSize: 1000 } // Prepare large batch of operations const operations: Array<{ path: string; value: unknown }> = []; for (let i = 0; i < 10000; i++) { operations.push({ path: `users.user_${i}`, value: { id: i, name: `User ${i}`, email: `user${i}@example.com`, age: 18 + (i % 60), active: i % 2 === 0 } }); } // Execute in parallel (automatically uses multi-core for >=100 items) const result = await db.batchSetParallel(operations); console.log('Batch Result:', result); // Output: { success: true, count: 10000, error: undefined } // Verify data const user42 = await db.get('users.user_42'); console.log('User 42:', user42); // Output: User 42: { id: 42, name: 'User 42', email: 'user42@example.com', age: 60, active: true } ``` -------------------------------- ### Subscribe to Data Changes (Pub/Sub) Source: https://github.com/sethunthunder111/jsondb-high/blob/main/docs/docs.html Receive real-time notifications when data at a specified path changes. The `subscribe` method returns an unsubscribe function to stop listening. ```javascript const unsubscribe = db.subscribe('users.*', (newVal) => { console.log('Changed:', newVal); }); ``` -------------------------------- ### Parallel Query Source: https://github.com/sethunthunder111/jsondb-high/blob/main/docs/docs.html Perform high-performance filtering using native Rust parallel iteration for faster query execution. ```APIDOC ## Parallel Query ### Description Perform high-performance filtering using native Rust parallel iteration for faster query execution, especially on large datasets. ### Method `parallelQuery` ### Endpoint N/A (In-memory operations) ### Parameters - `collection` (string) - The name of the collection to query. - `filters` (array) - An array of filter objects, each specifying: - `field` (string) - The field to filter on. - `op` (string) - The comparison operator (e.g., 'gte', 'eq', 'ne'). - `value` (any) - The value to compare against. ### Request Example ```javascript const activeAdults = await db.parallelQuery('users', [ { field: 'age', op: 'gte', value: 18 }, { field: 'status', op: 'eq', value: 'active' } ]); ``` ### Response #### Success Response (200) - `activeAdults` (array) - An array of documents that match all specified parallel filters. #### Response Example ```json [ { "id": 1, "name": "Alice", "age": 25, "status": "active" }, { "id": 4, "name": "David", "age": 35, "status": "active" } ] ``` ``` -------------------------------- ### Perform Parallel Queries for High Performance Source: https://github.com/sethunthunder111/jsondb-high/blob/main/docs/docs.html Leverage native Rust parallel iteration for high-performance data filtering. This method allows specifying multiple filter conditions to efficiently query large datasets. ```javascript const activeAdults = await db.parallelQuery('users', [ { field: 'age', op: 'gte', value: 18 }, { field: 'status', op: 'eq', value: 'active' } ]); ``` -------------------------------- ### Aggregations Source: https://github.com/sethunthunder111/jsondb-high/blob/main/docs/docs.html Perform aggregation operations like count, sum, and group by on your database collections. ```APIDOC ## Aggregations ### Description Perform aggregation operations like count, sum, and group by on your database collections. ### Method Various (internal methods) ### Endpoint N/A (In-memory operations) ### Parameters N/A ### Request Example ```javascript // Count all documents in the 'users' collection const count = db.query('users').count(); // Sum the 'amount' field for all documents in the 'orders' collection const total = db.query('orders').sum('amount'); // Group documents in the 'users' collection by the 'department' field const grouped = db.query('users').groupBy('department'); ``` ### Response #### Success Response (200) - `count` (number) - The total count of documents. - `total` (number) - The sum of the specified field. - `grouped` (object) - An object where keys are the group identifiers and values are arrays of documents belonging to that group. #### Response Example ```json // Example for count: 50 // Example for total: 1500.75 // Example for grouped: { "engineering": [ { "id": 1, "name": "Alice", "department": "engineering" }, { "id": 3, "name": "Charlie", "department": "engineering" } ], "marketing": [ { "id": 2, "name": "Bob", "department": "marketing" } ] } ``` ``` -------------------------------- ### Batch Operations Source: https://github.com/sethunthunder111/jsondb-high/blob/main/docs/docs.html Perform multiple database operations (set, delete) in a single batch for efficiency. ```APIDOC ## Batch Operations ### Description Perform multiple database operations (set, delete) in a single batch for efficiency. ### Method `batch`, `batchSetParallel` ### Endpoint N/A (In-memory operations) ### Parameters - `operations` (array) - An array of operation objects. Each object should have: - `type` (string) - 'set' or 'delete'. - `path` (string) - The path to the document or field. - `value` (any, optional) - The value to set (for 'set' operations). ### Request Example ```javascript // Perform a batch of set and delete operations await db.batch([ { type: 'set', path: 'logs.1', value: 'log data' }, { type: 'delete', path: 'temp.cache' } ]); // Perform parallel batch set operations (for large arrays) await db.batchSetParallel(largeArrayOfOperations); ``` ### Response #### Success Response (200) - No explicit return value, operation is performed asynchronously. #### Response Example N/A ``` -------------------------------- ### Paginate Data with paginate Helper Source: https://context7.com/sethunthunder111/jsondb-high/llms.txt Implement efficient pagination for API endpoints with the built-in `paginate` helper. This function returns data for a specific page along with complete pagination metadata, including total items, total pages, current page, limit, and indicators for next/previous pages. It simplifies the creation of paginated results. ```typescript const db = new JSONDatabase('db.json'); // Setup 50 users for (let i = 1; i <= 50; i++) { await db.set(`users.${i}`, { id: i, name: `User ${i}`, email: `user${i}@example.com` }); } interface User { id: number; name: string; email: string; } // Get first page (20 items per page) const page1 = await db.paginate('users', 1, 20); console.log('Page 1:', { items: page1.data.length, meta: page1.meta }); // Output: Page 1: { // items: 20, // meta: { total: 50, pages: 3, page: 1, limit: 20, hasNext: true, hasPrev: false } // } // Get second page const page2 = await db.paginate('users', 2, 20); console.log('Page 2 meta:', page2.meta); // Output: Page 2 meta: { total: 50, pages: 3, page: 2, limit: 20, hasNext: true, hasPrev: true } // Get last page const page3 = await db.paginate('users', 3, 20); console.log('Page 3:', { items: page3.data.length, hasNext: page3.meta.hasNext, hasPrev: page3.meta.hasPrev }); // Output: Page 3: { items: 10, hasNext: false, hasPrev: true } ``` -------------------------------- ### Build Complex Queries with Where Clauses Source: https://github.com/sethunthunder111/jsondb-high/blob/main/docs/docs.html Construct sophisticated queries by chaining various `where` conditions to filter data based on equality, inequality, ranges, array membership, string patterns, regex, and existence. ```javascript .where('field').eq(value) // Equal .where('field').ne(value) // Not equal .where('field').gt(value) // Greater than .where('field').gte(value) // Greater or equal .where('field').lt(value) // Less than .where('field').lte(value) // Less or equal .where('field').between(1, 10) // Between range .where('field').in([1, 2]) // In array .where('field').notIn([1]) // Not in array .where('field').contains('x') // String contains .where('field').startsWith('x')// String starts with .where('field').endsWith('x') // String ends with .where('field').matches(/^x/) // Regex match .where('field').exists() // Field exists .where('field').isNull() // Is null .where('field').isNotNull() // Is not null ``` -------------------------------- ### Perform Batch and Parallel Operations Source: https://github.com/sethunthunder111/jsondb-high/blob/main/docs/docs.html Execute multiple database operations atomically using `batch`. For high-performance scenarios with large datasets, `batchSetParallel` can be used. ```javascript await db.batch([ { type: 'set', path: 'logs.1', value: 'log data' }, { type: 'delete', path: 'temp.cache' } ]); // Parallel (High Performance) await db.batchSetParallel(largeArrayOfOperations); ``` -------------------------------- ### Find and Find All Records Source: https://github.com/sethunthunder111/jsondb-high/blob/main/docs/docs.html Retrieve single records or multiple records from a collection based on a provided predicate function. The `find` method returns the first matching record, while `findAll` returns all matching records. ```javascript const user = await db.find('users', u => u.age > 18); const adults = await db.findAll('users', u => u.age >= 18); ``` -------------------------------- ### Configure jsondb-high durability modes and WAL flushing Source: https://github.com/sethunthunder111/jsondb-high/blob/main/README.md Demonstrates configuring durability modes and Write-Ahead Log (WAL) flush intervals for jsondb-high. This allows balancing performance and data safety, with 'batched' mode recommended for its balance. ```typescript const db = new JSONDatabase('db.json', { durability: 'batched', // 'none' | 'lazy' | 'batched' | 'sync' walFlushMs: 10, // Sync every 10ms (Group Commit) lockMode: 'exclusive' }); ```