### Install JetDB Package Manager Source: https://github.com/zeative/jetdb/blob/main/README.md Instructions for installing the JetDB package using common Node.js package managers like npm, pnpm, and bun. ```bash npm install jetdb # or pnpm add jetdb # or bun add jetdb ``` -------------------------------- ### Chained Query Example in JetDB Source: https://github.com/zeative/jetdb/blob/main/README.md Provides a comprehensive example of chaining multiple query methods, including `where`, `whereNotIn`, `search`, `orderBy`, `select`, and `paginate`, to construct a complex query. ```typescript const result = await(await db.query('users')) .where('status', '=', 'active') .where('age', '>=', 18) .whereNotIn('role', ['banned', 'suspended']) .search('developer', ['bio', 'skills']) .orderBy('createdAt', 'desc') .select(['name', 'email', 'role']) .paginate(1, 20) .getPaginated(); console.log(result); ``` -------------------------------- ### Set and Get Data in JetDB Source: https://github.com/zeative/jetdb/blob/main/README.md Demonstrates the fundamental `set` and `get` operations in JetDB. The `set` method is used to store data under a specific key, while `get` retrieves it. It also shows how to perform a nested key search using `get`. ```typescript // Set a single value await db.set('config', { theme: 'dark', lang: 'en' }); // Get a value const config = await db.get('config'); // Get with nested key search const data = await db.get({ id: 1 }); // Searches through all data ``` -------------------------------- ### JetDB Query Builder: Complete Chain Example (TypeScript) Source: https://context7.com/zeative/jetdb/llms.txt Illustrates a comprehensive query chain in JetDB, combining filtering, searching, sorting, field selection, pagination, and result tapping to efficiently retrieve and process user data. ```typescript // Complex query combining multiple features const result = await db.query('users') // Filter active adult users .where('status', '=', 'active') .where('age', '>=', 18) // Exclude banned/suspended .whereNotIn('role', ['banned', 'suspended']) // Search for developers .search('developer', ['bio', 'skills', 'jobTitle']) // Only verified emails .whereNotNull('verifiedAt') // Sort by join date .orderBy('createdAt', 'desc') // Select specific fields .select(['name', 'email', 'role', 'age']) // Get page 1, 20 per page .paginate(1, 20) // Log intermediate results .tap((users) => console.log(`Processing ${users.length} users`)) // Execute and get paginated result .getPaginated(); console.log(`Showing ${result.data.length} of ${result.total} users`); console.log(`Page ${result.page} of ${result.totalPages}`); console.log(`Has next: ${result.hasNext}, Has prev: ${result.hasPrev}`); ``` -------------------------------- ### Manual Data Flush in JetDB Source: https://github.com/zeative/jetdb/blob/main/README.md Provides an example of manually forcing the database to write all pending changes to disk immediately using the `db.flush` method. ```typescript // Force write to disk immediately await db.flush(); ``` -------------------------------- ### Get Data from JetDB (TypeScript) Source: https://context7.com/zeative/jetdb/llms.txt Shows how to retrieve data from JetDB using different methods. You can fetch data by a string key, perform nested key searches, retrieve all data, or leverage automatic caching for faster access on subsequent calls. The `get` method returns the data associated with the key, or `undefined` if not found. ```typescript // Get by string key const users = await db.get('users'); console.log(users); // Array of user objects // Get with nested key search (searches through all data) const user = await db.get({ id: 2 }); console.log(user); // { id: 2, name: 'Bob Smith', ... } // Get all data in database const allData = await db.all(); console.log(allData); // [['users', [...]], ['config', {...}], ...] // Get with caching (automatic) const config = await db.get('config'); // Second call hits cache - 397x faster const configAgain = await db.get('config'); ``` -------------------------------- ### Manage Cache and Get Statistics with JetDB Source: https://context7.com/zeative/jetdb/llms.txt Details how to interact with JetDB's cache management features, including retrieving cache statistics, access statistics for hot/cold data, clearing the cache, and manually flushing data to disk. This allows for optimization of data access patterns and ensures data persistence. ```typescript // Get cache statistics const cacheStats = db.getCacheStats(); console.log(cacheStats); // { size: 150, max: 1000, hits: 3547 } // Get access statistics (hot/cold data tracking) const accessStats = db.getAccessStats(); console.log(accessStats); // [ // { key: 'users', count: 245, lastAccess: 1703001234567, isHot: true }, // { key: 'config', count: 12, lastAccess: 1703001234500, isHot: true }, // { key: 'archive', count: 2, lastAccess: 1703001230000, isHot: false } // ] // Clear LRU cache (data remains in database) db.clearCache(); console.log('Cache cleared - next access will reload from disk'); // Manual flush to disk (useful with flushMode: 'manual') await db.flush(); console.log('All changes written to disk'); // Flush happens automatically with 'sync' or 'debounce' modes // Use manual mode for fine-grained control over when data is persisted ``` -------------------------------- ### Get All Data in JetDB Source: https://github.com/zeative/jetdb/blob/main/README.md Retrieves all data currently stored in the JetDB database. This operation can be resource-intensive for large databases. ```typescript // Get all data in database const allData = await db.all(); ``` -------------------------------- ### QueryBuilder: Retrieval Methods in JetDB Source: https://github.com/zeative/jetdb/blob/main/README.md Executes the constructed query and retrieves the results. Includes aliases for common retrieval methods and functions to get the first or last matching record. ```typescript // Execute query const results = await query.execute(); const results = await query.get(); // alias const results = await query.all(); // alias // First/Last const first = await query.first(); const last = await query.last(); // Find with predicate const user = await query.find((u) => u.email === 'john@example.com'); const index = await query.findIndex((u) => u.id === 5); ``` -------------------------------- ### Initialize JetDB with Default Settings Source: https://github.com/zeative/jetdb/blob/main/README.md Demonstrates the basic initialization of a JetDB instance using the default configuration. This creates a database instance connected to a specified file path. ```typescript import { JetDB } from 'jetdb'; // Create database instance const db = new JetDB('data/data.json'); // Set data await db.set('users', [ { id: 1, name: 'John Doe', email: 'john@example.com', age: 28 }, { id: 2, name: 'Jane Smith', email: 'jane@example.com', age: 32 }, ]); // Get data const users = await db.get('users'); console.log(users); // Query with fluent API const result = await db.query('users').where('age', '>', 25).orderBy('name', 'asc').limit(10).get(); console.log(result); ``` -------------------------------- ### Configure JetDB with Advanced Options Source: https://github.com/zeative/jetdb/blob/main/README.md Illustrates the initialization of JetDB with a comprehensive set of configuration options, including chunk size, flush mode, debounce delay, cache size, compression, serialization, indexing, and hot data thresholds. ```typescript const db = new JetDB('data/data.json', { size: 5 * 1024 * 1024, // 5MB chunks flushMode: 'debounce', debounceMs: 500, cacheSize: 5000, compression: 'deflate', serialization: 'msgpack', enableIndexing: true, hotThreshold: 20, }); ``` -------------------------------- ### Initialize JetDB with Factory and Custom Options Source: https://github.com/zeative/jetdb/blob/main/README.md Shows how to create a JetDB instance using the factory function `createJetDB`, allowing for custom configuration options such as cache size, compression, and serialization. ```typescript import { createJetDB } from 'jetdb'; const db = createJetDB('data/data.json', { cacheSize: 2000, compression: 'deflate', serialization: 'msgpack', }); ``` -------------------------------- ### Initialize JetDB Database (TypeScript) Source: https://context7.com/zeative/jetdb/llms.txt Demonstrates how to initialize a JetDB database instance using basic and full configurations. It covers setting chunk size, flush mode, cache size, compression, serialization, indexing, and event listeners for database changes, flushes, and loads. Dependencies include the 'jetdb' package. ```typescript import { JetDB, createJetDB } from 'jetdb'; // Basic initialization const db = new JetDB('data/mydb.json'); // With full configuration const db = createJetDB('data/mydb.json', { size: 5 * 1024 * 1024, // 5MB chunk size flushMode: 'debounce', // 'manual' | 'sync' | 'debounce' debounceMs: 500, // Debounce delay in ms cacheSize: 5000, // LRU cache max items compression: 'deflate', // 'deflate' | 'none' serialization: 'msgpack', // 'msgpack' | 'json' enableIndexing: true, // Enable index support hotThreshold: 20 // Access count for hot data }); // Listen to database events db.on('change', ({ key, value, action }) => { console.log(`Action: ${action}, Key: ${key}`); }); db.on('flush', () => { console.log('Data written to disk'); }); db.on('loaded', () => { console.log('Database loaded from disk'); }); ``` -------------------------------- ### QueryBuilder: Distinct Methods in JetDB Source: https://github.com/zeative/jetdb/blob/main/README.md Retrieves unique records from the query results. Can be used to get distinct records overall or distinct values for a specific field. ```typescript // Distinct records query.distinct(); // Distinct by field query.distinct('email'); query.unique('category'); // alias for distinct ``` -------------------------------- ### Memory-Efficient Data Streaming in JetDB Source: https://github.com/zeative/jetdb/blob/main/README.md Illustrates how to stream data from the database without loading the entire dataset into memory, using `streamAll` for all data and `streamKey` for specific keys. ```typescript // Stream all data for await (const [key, value] of db.streamAll()) { console.log(`${key}:`, value); } // Stream specific key for await (const item of db.streamKey('largeDataset')) { processItem(item); } ``` -------------------------------- ### Implement Reactive Patterns with JetDB Event System Source: https://context7.com/zeative/jetdb/llms.txt Demonstrates how to use JetDB's event system to build reactive applications. It shows how to listen for various events like data changes ('change'), database flushes ('flush'), loads ('loaded'), and cache clears ('cacheCleared') to trigger side effects and respond to database operations in real-time. ```typescript // Listen to all data changes db.on('change', ({ key, value, action }) => { console.log(`[${action.toUpperCase()}] ${key}`); // React to specific changes if (key === 'users' && action === 'set') { console.log(`User list updated with ${value.length} users`); } // Trigger side effects if (action === 'delete') { logDeletion(key); } }); // Listen to flush events (data written to disk) db.on('flush', () => { const timestamp = new Date().toISOString(); console.log(`[${timestamp}] Database flushed to disk`); updateBackupStatus(); }); // Listen to load events (database initialized) db.on('loaded', () => { console.log('Database loaded and ready'); initializeApplication(); }); // Listen to cache clear events db.on('cacheCleared', () => { console.log('Cache was cleared'); logCacheEvent(); }); // Events enable building reactive applications // that respond to database changes in real-time ``` -------------------------------- ### Reacting to Database Events in JetDB Source: https://github.com/zeative/jetdb/blob/main/README.md Demonstrates how to subscribe to various database events like 'change', 'flush', and 'loaded' using the `db.on` method to react to data modifications and system operations. ```typescript // Listen to changes db.on('change', ({ key, value, action }) => { console.log(`${action} operation on ${key}`); }); // Listen to flush events db.on('flush', () => { console.log('Data written to disk'); }); // Listen to load events db.on('loaded', () => { console.log('Data loaded from disk'); }); ``` -------------------------------- ### Indexing for Fast Lookups in JetDB Source: https://github.com/zeative/jetdb/blob/main/README.md Shows how to create, use, and drop indexes for significantly faster data retrieval. The `getByIndex` method leverages created indexes for efficient querying. ```typescript // Create index on field await db.createIndex('users', 'email'); // Query using index (100-1000x faster!) const users = await db.getByIndex('users', 'email', 'john@example.com'); // Drop index await db.dropIndex('users', 'email'); ``` -------------------------------- ### Data Transformation and Full-Text Search in JetDB Source: https://github.com/zeative/jetdb/blob/main/README.md Illustrates data transformation using `transform` and `map` methods to reshape query results. Shows how to perform full-text searches on specified fields. ```typescript // Transform/Map query.transform((user) => ({ fullName: `${user.firstName} ${user.lastName}`, email: user.email, })); query.map((user) => user.email.toLowerCase()); // Full-text search query.search('john', ['name', 'email', 'bio']); ``` -------------------------------- ### Conditional Queries in JetDB Source: https://github.com/zeative/jetdb/blob/main/README.md Demonstrates how to conditionally execute query clauses based on boolean flags using `when` and `unless` methods. Also shows `tap` for inspecting intermediate results and `dump`/`dd` for debugging. ```typescript // Conditional query query.when(userIsAdmin, (qb) => qb.where('role', '=', 'admin')); query.unless(userIsGuest, (qb) => qb.where('verified', '=', true)); // Tap (inspect intermediate results without breaking chain) query.tap((results) => console.log('Current results:', results.length)); // Dump and die (debug) await query.dump().get(); // Logs results await query.dd(); // Dumps and exits ``` -------------------------------- ### Manual Read and Write Operations in TypeScript Source: https://context7.com/zeative/jetdb/llms.txt Demonstrates how to manually read data from disk using `db.read()`, write data to disk using `db.write()`, and the preferred method `db.flush()` for controlled persistence. These operations are rarely needed as JetDB typically handles persistence automatically. `flush()` is recommended for better control over writes and to leverage debounce. ```typescript // Manual read from disk (rare - usually automatic) const dataMap = await db.read(); console.log('Database reloaded from disk'); // Manual write to disk (use flush() instead for better control) await db.write(); console.log('Database written to disk'); // Flush is preferred - respects debounce and prevents multiple writes await db.flush(); // These low-level operations are typically not needed // The database handles persistence automatically based on flushMode ``` -------------------------------- ### Create and Query Indexes with JetDB Source: https://context7.com/zeative/jetdb/llms.txt Explains how to create indexes on frequently queried fields for faster data retrieval using JetDB's `createIndex` and `getByIndex` methods. It also covers dropping indexes when they are no longer needed. Indexes significantly speed up lookups compared to full data scans. ```typescript // Create index on frequently queried field await db.createIndex('users', 'email'); await db.createIndex('users', 'username'); await db.createIndex('products', 'sku'); // Query using index (47x+ faster than scanning) const usersByEmail = await db.getByIndex('users', 'email', 'alice@example.com'); console.log(usersByEmail); // Instant lookup const productBySku = await db.getByIndex('products', 'sku', 'WIDGET-001'); console.log(productBySku); // Drop index when no longer needed await db.dropIndex('users', 'email'); // Note: Indexes are automatically maintained on data changes // Best for fields that rarely change but are frequently queried ``` -------------------------------- ### Query Builder - Sorting and Pagination Source: https://context7.com/zeative/jetdb/llms.txt Explains how to sort query results by single or multiple fields and how to implement pagination using limit, offset, or convenient paginate methods. ```APIDOC ## Query Builder - Sorting and Pagination ### Description Provides functionality to order query results and paginate through large datasets. ### Method - `query(tableName: string)`: Initializes a query. - `.orderBy(field: string, direction: 'asc' | 'desc'): QueryBuilder` - `.sortBy(fields: string[], directions: ('asc' | 'desc')[]): QueryBuilder` - `.limit(count: number): QueryBuilder` - `.offset(count: number): QueryBuilder` - `.paginate(page: number, perPage: number): QueryBuilder` - `.get(): Promise` - `.getPaginated(): Promise<{ data: T[], total: number, page: number, perPage: number, totalPages: number, hasNext: boolean, hasPrev: boolean }>` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```typescript // Sort by single field const sortedByName = await db.query('users') .orderBy('name', 'asc') .get(); // Sort by multiple fields const sortedMultiple = await db.query('users') .sortBy(['lastName', 'firstName'], ['asc', 'asc']) .get(); // Pagination with limit and offset const page2 = await db.query('users') .limit(20) .offset(20) .get(); // Convenient pagination const page3 = await db.query('users') .paginate(3, 20) // page 3, 20 items per page .orderBy('createdAt', 'desc') .getPaginated(); console.log(page3); // { // data: [/* 20 users */], // total: 156, // page: 3, // perPage: 20, // totalPages: 8, // hasNext: true, // hasPrev: true // } ``` ### Response #### Success Response (200) - `result` (array of objects) - For `.get()` method, returns the sorted/paginated records. - `paginatedResult` (object) - For `.getPaginated()` method, returns an object containing data, pagination info, and navigation flags. #### Response Example ```json // For .get() [ { "id": 1, "name": "Alice", ... }, { "id": 2, "name": "Bob", ... } ] // For .getPaginated() { "data": [ { "id": 41, "name": "Charlie", ... }, ... ], "total": 156, "page": 3, "perPage": 20, "totalPages": 8, "hasNext": true, "hasPrev": true } ``` ``` -------------------------------- ### Cache Statistics and Management in JetDB Source: https://github.com/zeative/jetdb/blob/main/README.md Shows how to retrieve cache statistics (size, hits) and access statistics (hot/cold data) using `getCacheStats` and `getAccessStats`. Also includes a method to clear the LRU cache. ```typescript // Get cache statistics const stats = db.getCacheStats(); console.log(stats); // { size: 150, max: 1000, hits: 150 } // Get access statistics (hot/cold data) const accessStats = db.getAccessStats(); console.log(accessStats); // [ // { key: 'users', count: 45, lastAccess: 1703001234567, isHot: true }, // { key: 'config', count: 3, lastAccess: 1703001234500, isHot: false } // ] // Clear LRU cache db.clearCache(); ``` -------------------------------- ### Stream Large Datasets with JetDB Source: https://context7.com/zeative/jetdb/llms.txt Illustrates how to efficiently process large datasets without loading them entirely into memory using JetDB's streaming capabilities. It shows how to stream all database entries or specific keys, enabling memory-efficient handling of substantial amounts of data. ```typescript // Stream all database entries let totalRecords = 0; for await (const [key, value] of db.streamAll()) { console.log(`Processing ${key}:`, value); totalRecords++; // Process one record at a time without loading all into memory await processRecord(key, value); } console.log(`Processed ${totalRecords} total records`); // Stream specific key (useful for large arrays) let processedUsers = 0; for await (const user of db.streamKey('users')) { // Process one user at a time if (user.status === 'inactive' && user.lastLogin < Date.now() - 90 * 24 * 60 * 60 * 1000) { await sendReactivationEmail(user.email); processedUsers++; } } console.log(`Sent ${processedUsers} reactivation emails`); // Streaming is memory-efficient for processing large datasets // that don't fit in memory all at once ``` -------------------------------- ### JetDB Query Builder - Basic Filtering Source: https://context7.com/zeative/jetdb/llms.txt Shows how to use the JetDB query builder for basic filtering. This includes simple where conditions, OR conditions, array operations (IN/NOT IN), range queries (BETWEEN), pattern matching (LIKE), null checks (IS NULL/IS NOT NULL), and custom filter functions. ```typescript // Basic where conditions const activeAdults = await db.query('users') .where('age', '>', 25) .where('status', '=', 'active') .get(); // OR conditions const adminsOrModerators = await db.query('users') .where('role', '=', 'admin') .orWhere('role', '=', 'moderator') .get(); // Array operations const specificUsers = await db.query('users') .whereIn('status', ['active', 'pending', 'verified']) .whereNotIn('role', ['banned', 'suspended', 'deleted']) .get(); // Range queries const workingAge = await db.query('users') .whereBetween('age', 18, 65) .get(); // Pattern matching with LIKE const gmailUsers = await db.query('users') .whereLike('email', '%@gmail.com') .get(); // Null checks const unverifiedUsers = await db.query('users') .whereNull('verifiedAt') .whereNotNull('email') .get(); // Custom filter function const highValueUsers = await db.query('users') .filter((user) => user.points > 1000 && user.purchases > 5) .get(); ``` -------------------------------- ### JetDB Query Builder - Selection and Aggregation Source: https://context7.com/zeative/jetdb/llms.txt Covers selection and aggregation methods in the JetDB query builder. Allows selecting specific fields, plucking single field values, and performing aggregate functions like count, sum, average, min, and max. Also includes grouping and having clauses for advanced data analysis. ```typescript // Select specific fields const userSummaries = await db.query('users') .select(['name', 'email', 'role']) .where('status', '=', 'active') .get(); // Pluck single field values const allEmails = await db.query('users') .pluck('email') .get(); console.log(allEmails); // ['alice@example.com', 'bob@example.com', ...] // Count records const totalUsers = await db.query('users').count(); const activeUsers = await db.query('users') .where('status', '=', 'active') .count(); // Sum, average, min, max const totalAge = await db.query('users').sum('age'); const avgAge = await db.query('users').avg('age'); const youngest = await db.query('users').min('age'); const oldest = await db.query('users').max('age'); // Combined aggregation const ageStats = await db.query('users') .where('status', '=', 'active') .aggregate('age'); console.log(ageStats); // { count: 100, sum: 3250, avg: 32.5, min: 18, max: 65 } // Group by field const usersByRole = await db.query('users').groupBy('role'); console.log(usersByRole); // { // admin: [{ id: 1, name: 'Alice', role: 'admin' }, ...], // user: [{ id: 2, name: 'Bob', role: 'user' }, ...], // moderator: [...] // } // Having clause (filter after grouping) const popularDepartments = await db.query('employees') .groupBy('department') .having('count', '>', 5); ``` -------------------------------- ### Query Builder Source: https://github.com/zeative/jetdb/blob/main/README.md Construct complex queries with a fluent API for filtering, sorting, paginating, and aggregating data. ```APIDOC ## Query Builder ### Description Provides a fluent API for constructing and executing complex queries against your data. ### Initialization #### Method `db.query(collection)` #### Parameters - **collection** (string) - Required - The name of the collection to query. #### Request Example ```typescript const query = await db.query('users'); ``` ### Filtering Methods #### `where(field, operator, value)` Applies a basic filter condition. - **field** (string) - The field to filter on. - **operator** (string) - The comparison operator (e.g., '=', '>', '<', 'like'). - **value** (any) - The value to compare against. #### `orWhere(field, operator, value)` Applies an OR condition to the query. #### `whereIn(field, values)` Filters records where the field's value is within a given array. - **values** (array) - An array of values to check against. #### `whereNotIn(field, values)` Filters records where the field's value is NOT within a given array. #### `whereBetween(field, min, max)` Filters records where the field's value is between two values (inclusive). #### `whereLike(field, pattern)` Filters records using a LIKE pattern. #### `whereNull(field)` Filters records where the specified field is null. #### `whereNotNull(field)` Filters records where the specified field is not null. #### `filter(predicate)` Applies a custom JavaScript predicate function for filtering. - **predicate** (function) - A function that accepts a record and returns true or false. ### Sorting #### `sort(field, direction)` or `orderBy(field, direction)` Sorts the results by a single field. - **field** (string) - The field to sort by. - **direction** (string) - 'asc' for ascending, 'desc' for descending. #### `sortBy(fields, directions)` Sorts the results by multiple fields. - **fields** (array) - An array of field names. - **directions** (array) - An array of corresponding sort directions ('asc' or 'desc'). ### Pagination & Limiting #### `limit(count)` or `take(count)` Limits the number of results returned. - **count** (number) - The maximum number of results. #### `offset(count)` or `skip(count)` Skips a specified number of results. - **count** (number) - The number of results to skip. #### `paginate(page, perPage)` Sets the pagination parameters. - **page** (number) - The current page number. - **perPage** (number) - The number of results per page. #### `getPaginated()` Executes the query with pagination and returns paginated results. ### Selection #### `select(fields)` Specifies which fields to include in the results. - **fields** (array) - An array of field names to select. #### `pluck(field)` Retrieves only the values of a specific field from all records. ### Aggregation #### `count()` Returns the total number of records matching the query. #### `sum(field)` Calculates the sum of values for a specified field. #### `avg(field)` Calculates the average of values for a specified field. #### `min(field)` Finds the minimum value for a specified field. #### `max(field)` Finds the maximum value for a specified field. #### `aggregate(field)` Performs multiple aggregations (count, sum, avg, min, max) on a field. #### `having(field, operator, value)` Applies a filter condition after grouping (used with `groupBy`). ### Grouping #### `groupBy(field)` Groups the results by the values in a specified field. ### Distinct #### `distinct()` Returns only distinct records. #### `distinct(field)` or `unique(field)` Returns distinct values for a specified field. ### Retrieval #### `execute()`, `get()`, or `all()` Executes the query and returns all matching records. #### `first()` Returns the first record matching the query. #### `last()` Returns the last record matching the query. #### `find(predicate)` Finds the first record that satisfies a given predicate function. #### `findIndex(predicate)` Finds the index of the first record that satisfies a given predicate function. ### Existence Checks #### `exists()` Returns true if the query returns any results, false otherwise. #### `isEmpty()` Returns true if the query returns no results, false otherwise. ### Utilities #### `chunk(size)` Splits the query results into chunks of a specified size. #### `random(count)` Returns a specified number of random records from the results. ### Chaining Example ```typescript // Example: Find active users older than 25, sorted by name, and get the first 10 const users = await db.query('users') .where('status', '=', 'active') .where('age', '>', 25) .orderBy('name', 'asc') .limit(10) .get(); ``` ``` -------------------------------- ### Query Builder - Basic Filtering Source: https://context7.com/zeative/jetdb/llms.txt Demonstrates basic filtering capabilities of the query builder, including standard comparisons, OR conditions, array operations, range queries, pattern matching, null checks, and custom filter functions. ```APIDOC ## Query Builder - Basic Filtering ### Description Enables complex filtering of data using various conditions within the query builder. ### Method - `query(tableName: string)`: Initializes a query. - `.where(field: string, operator: string, value: any): QueryBuilder` - `.orWhere(field: string, operator: string, value: any): QueryBuilder` - `.whereIn(field: string, values: any[]): QueryBuilder` - `.whereNotIn(field: string, values: any[]): QueryBuilder` - `.whereBetween(field: string, range: [any, any]): QueryBuilder` - `.whereLike(field: string, pattern: string): QueryBuilder` - `.whereNull(field: string): QueryBuilder` - `.whereNotNull(field: string): QueryBuilder` - `.filter(predicate: (item: T) => boolean): QueryBuilder` - `.get(): Promise` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```typescript // Basic where conditions const activeAdults = await db.query('users') .where('age', '>', 25) .where('status', '=', 'active') .get(); // OR conditions const adminsOrModerators = await db.query('users') .where('role', '=', 'admin') .orWhere('role', '=', 'moderator') .get(); // Array operations const specificUsers = await db.query('users') .whereIn('status', ['active', 'pending', 'verified']) .whereNotIn('role', ['banned', 'suspended', 'deleted']) .get(); // Range queries const workingAge = await db.query('users') .whereBetween('age', 18, 65) .get(); // Pattern matching with LIKE const gmailUsers = await db.query('users') .whereLike('email', '%@gmail.com') .get(); // Null checks const unverifiedUsers = await db.query('users') .whereNull('verifiedAt') .whereNotNull('email') .get(); // Custom filter function const highValueUsers = await db.query('users') .filter((user) => user.points > 1000 && user.purchases > 5) .get(); ``` ### Response #### Success Response (200) - `result` (array of objects) - An array containing the filtered records matching the query criteria. #### Response Example ```json [ { "id": 1, "name": "Alice", "age": 30, "status": "active", ... }, { "id": 2, "name": "Bob", "age": 28, "status": "active", ... } ] ``` ``` -------------------------------- ### Type-Safe Queries with Generics in JetDB Source: https://github.com/zeative/jetdb/blob/main/README.md Demonstrates how to define TypeScript interfaces for data models and use them with the `db.query` method to enable type-safe querying and ensure results conform to the defined interface. ```typescript interface User { id: number; name: string; email: string; age: number; } const users = await(await db.query('users')) .where('age', '>', 18) .get(); // users is typed as User[] ``` -------------------------------- ### QueryBuilder: Pagination and Limiting in JetDB Source: https://github.com/zeative/jetdb/blob/main/README.md Provides methods to control the number of records returned, skip records, and implement pagination. Supports retrieving paginated results with metadata. ```typescript // Limit results query.limit(10); query.take(5); // Skip results query.offset(20); query.skip(10); // Paginate query.paginate(2, 20); // page 2, 20 per page // Get paginated result const result = await query.getPaginated(); // { ... } ``` -------------------------------- ### JetDB Query Builder - Sorting and Pagination Source: https://context7.com/zeative/jetdb/llms.txt Demonstrates sorting and pagination capabilities within the JetDB query builder. Supports sorting by a single field or multiple fields in ascending/descending order, and provides methods for limit/offset pagination as well as convenient paginate functionality. ```typescript // Sort by single field const sortedByName = await db.query('users') .orderBy('name', 'asc') .get(); // Sort by multiple fields const sortedMultiple = await db.query('users') .sortBy(['lastName', 'firstName'], ['asc', 'asc']) .get(); // Pagination with limit and offset const page2 = await db.query('users') .limit(20) .offset(20) .get(); // Convenient pagination const page3 = await db.query('users') .paginate(3, 20) // page 3, 20 items per page .orderBy('createdAt', 'desc') .getPaginated(); console.log(page3); // { // data: [/* 20 users */], // total: 156, // page: 3, // perPage: 20, // totalPages: 8, // hasNext: true, // hasPrev: true // } ``` -------------------------------- ### Query Builder - Selection and Aggregation Source: https://context7.com/zeative/jetdb/llms.txt Covers selecting specific fields, plucking single field values, and performing aggregations like count, sum, average, min, max, groupBy, and having clauses. ```APIDOC ## Query Builder - Selection and Aggregation ### Description Allows for specifying which fields to retrieve and performing aggregate calculations on data. ### Method - `query(tableName: string)`: Initializes a query. - `.select(fields: string[]): QueryBuilder` - `.pluck(field: string): QueryBuilder` - `.count(): Promise` - `.sum(field: string): Promise` - `.avg(field: string): Promise` - `.min(field: string): Promise` - `.max(field: string): Promise` - `.aggregate(field: string): Promise<{ count: number, sum: number, avg: number, min: number, max: number }>` - `.groupBy(field: string): Promise>` - `.having(field: string, operator: string, value: any): QueryBuilder` - `.get(): Promise` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```typescript // Select specific fields const userSummaries = await db.query('users') .select(['name', 'email', 'role']) .where('status', '=', 'active') .get(); // Pluck single field values const allEmails = await db.query('users') .pluck('email') .get(); console.log(allEmails); // ['alice@example.com', 'bob@example.com', ...] // Count records const totalUsers = await db.query('users').count(); const activeUsers = await db.query('users') .where('status', '=', 'active') .count(); // Sum, average, min, max const totalAge = await db.query('users').sum('age'); const avgAge = await db.query('users').avg('age'); const youngest = await db.query('users').min('age'); const oldest = await db.query('users').max('age'); // Combined aggregation const ageStats = await db.query('users') .where('status', '=', 'active') .aggregate('age'); console.log(ageStats); // { count: 100, sum: 3250, avg: 32.5, min: 18, max: 65 } // Group by field const usersByRole = await db.query('users').groupBy('role'); console.log(usersByRole); // { // admin: [{ id: 1, name: 'Alice', role: 'admin' }, ...], // user: [{ id: 2, name: 'Bob', role: 'user' }, ...], // moderator: [...] // } // Having clause (filter after grouping) const popularDepartments = await db.query('employees') .groupBy('department') .having('count', '>', 5); ``` ### Response #### Success Response (200) - `result` (array of objects or single value) - Depending on the method called (`.get()`, `.count()`, `.pluck()`, `.aggregate()`, etc.), returns selected fields, counts, or aggregated data. - `groupedResult` (object) - For `.groupBy()` method, returns an object where keys are the group identifiers and values are arrays of records belonging to that group. #### Response Example ```json // For .select() [ { "name": "Alice", "email": "alice@example.com", "role": "admin" }, { "name": "Bob", "email": "bob@example.com", "role": "user" } ] // For .pluck() ["alice@example.com", "bob@example.com"] // For .count() 156 // For .aggregate() { "count": 100, "sum": 3250, "avg": 32.5, "min": 18, "max": 65 } // For .groupBy() { "admin": [ { "id": 1, "name": "Alice", "role": "admin" }, ... ], "user": [ { "id": 2, "name": "Bob", "role": "user" }, ... ] } ``` ``` -------------------------------- ### Batch Set Key-Value Pairs in JetDB Source: https://context7.com/zeative/jetdb/llms.txt Illustrates how to perform batch set operations in JetDB, allowing for the efficient insertion or update of multiple key-value pairs simultaneously. These operations are atomic per key and automatically scheduled for flushing based on the configured flushMode. ```typescript // Batch set multiple key-value pairs await db.batchSet([ { key: 'setting:theme', value: 'dark' }, { key: 'setting:language', value: 'en' }, { key: 'setting:notifications', value: true }, { key: 'cache:timestamp', value: Date.now() } ]); // All operations are atomic per key // Automatically schedules flush based on flushMode ``` -------------------------------- ### Perform ACID Transactions with JetDB Source: https://context7.com/zeative/jetdb/llms.txt Demonstrates how to execute ACID transactions using JetDB's `transaction` method. It shows simple transactions with automatic commit/rollback and more complex transactions involving multiple operations. Transactions ensure data consistency by guaranteeing that either all operations within the transaction are applied, or none are. ```typescript // Simple transaction with automatic commit/rollback try { await db.transaction(async (tx) => { // Read current balances const account1 = await tx.get('account:1'); const account2 = await tx.get('account:2'); // Transfer funds await tx.set('account:1', { ...account1, balance: account1.balance - 100 }); await tx.set('account:2', { ...account2, balance: account2.balance + 100 }); // Auto-commits on success }); console.log('Transaction completed successfully'); } catch (error) { // Auto-rollback on error console.error('Transaction failed and was rolled back:', error); } // Complex transaction with multiple operations try { await db.transaction(async (tx) => { // Update user const user = await tx.get('user:123'); await tx.set('user:123', { ...user, credits: user.credits - 50 }); // Create order await tx.set('order:456', { userId: 123, amount: 50, status: 'pending', createdAt: Date.now() }); // Update inventory const product = await tx.get('product:789'); await tx.set('product:789', { ...product, stock: product.stock - 1 }); // All operations succeed or none do }); } catch (error) { console.error('Order transaction failed:', error); } ``` -------------------------------- ### Database Transactions in JetDB Source: https://github.com/zeative/jetdb/blob/main/README.md Demonstrates how to perform ACID transactions with snapshot isolation using the `db.transaction` method. Operations within the transaction are isolated and automatically commit on success or rollback on error. ```typescript try { await db.transaction(async (tx) => { // All operations in tx are isolated await tx.set('account:1', { balance: 900 }); await tx.set('account:2', { balance: 1100 }); // Auto-commit on success }); } catch (error) { // Auto-rollback on error console.error('Transaction failed:', error); } ``` -------------------------------- ### JetDB Query Builder: Advanced Features (TypeScript) Source: https://context7.com/zeative/jetdb/llms.txt Demonstrates advanced query building capabilities in JetDB, including full-text search across multiple fields, retrieving distinct records, building conditional queries using 'when' and 'unless', transforming query results, tapping into results for logging, and debugging queries with 'dump' and 'dd'. ```typescript // Full-text search across multiple fields const searchResults = await db.query('users') .search('john developer', ['name', 'email', 'bio', 'skills']) .get(); // Distinct records const uniqueEmails = await db.query('users') .distinct('email') .get(); // All distinct records const uniqueUsers = await db.query('users') .distinct() .get(); // Conditional query building const query = db.query('users') .when(userIsAdmin, (qb) => qb.where('role', '=', 'admin')) .unless(includeDeleted, (qb) => qb.whereNull('deletedAt')); const results = await query.get(); // Transform results const userCards = await db.query('users') .where('status', '=', 'active') .transform((user) => ({ displayName: `${user.name} (${user.role})`, contact: user.email, isAdmin: user.role === 'admin' })) .get(); // Tap into results (for logging/debugging without breaking chain) const users = await db.query('users') .where('status', '=', 'active') .tap((results) => console.log(`Found ${results.length} active users`)) .orderBy('name', 'asc') .get(); // Debug queries await db.query('users') .where('age', '>', 18) .dump() // Logs query state .get(); // Dump and die (for debugging) await db.query('users') .where('status', '=', 'active') .dd(); // Logs results and exits ``` -------------------------------- ### Batch Operations Source: https://context7.com/zeative/jetdb/llms.txt This section details how to perform batch set operations for multiple key-value pairs. ```APIDOC ## Batch Operations ### Description Allows for setting multiple key-value pairs in a single atomic operation. ### Method - `batchSet(items: { key: string, value: any }[]): Promise` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - `items` (array of objects) - An array where each object contains a `key` (string) and a `value` (any). ### Request Example ```typescript await db.batchSet([ { key: 'setting:theme', value: 'dark' }, { key: 'setting:language', value: 'en' }, { key: 'setting:notifications', value: true }, { key: 'cache:timestamp', value: Date.now() } ]); ``` ### Response #### Success Response (200) No explicit response body, operation is asynchronous. #### Response Example None ```