### Install Nitrobase with npm Source: https://github.com/alwatr/nitrobase/blob/next/packages/nitrobase/README.md This command installs the Alwatr Nitrobase package using npm. Ensure you have Node.js and npm installed on your system. ```bash npm install @alwatr/nitrobase ``` -------------------------------- ### Nitrobase User Management TypeScript Example Source: https://github.com/alwatr/nitrobase/blob/next/packages/user-management/README.md Demonstrates how to use the Nitrobase User Management module in TypeScript. It covers initialization, creating new users, checking for user existence, retrieving user data, verifying tokens, saving data, and listing user IDs. Requires @alwatr/nitrobase. ```typescript import {AlwatrNitrobase, NitrobaseUserManagement, type NewUser} from '@alwatr/nitrobase'; // Define your user data structure interface MyUserData { name: string; email: string; // ... other properties } // Initialize Nitrobase const nitrobase = new AlwatrNitrobase({ // ... your nitrobase configuration }); // Initialize User Management await NitrobaseUserManagement.initialize(nitrobase); const userManagement = new NitrobaseUserManagement(nitrobase); // Create a new user const newUser: NewUser = { userId: 'user123', userToken: 'some_secure_token', data: { name: 'John Doe', email: 'john.doe@example.com', }, }; await userManagement.newUser(newUser); // Check if a user exists const userExists = await userManagement.hasUser('user123'); console.log('User exists:', userExists); // Output: User exists: true // Get user data const userData = await userManagement.getUserData('user123'); console.log('User data:', userData); // Output: User data: { name: 'John Doe', email: 'john.doe@example.com' } // Verify user token const isValidToken = await userManagement.verifyUserToken('user123', 'some_secure_token'); console.log('Is valid token:', isValidToken); // Output: Is valid token: true // Save user data (after modifications) userData.email = 'john.updated@example.com' userManagement.save('user123') // Background save userManagement.saveImmediate('user123') // Immediate save (blocking) // Get all user IDs const userIds = await userManagement.userIds(); for await (const userId of userIds) { console.log('User ID:', userId); } // Get user directory const userDir = await userManagement.getUserDirectory('user123'); console.log('User directory:', userDir); ``` -------------------------------- ### Create and Manage Collections with AlwatrNitrobase Source: https://context7.com/alwatr/nitrobase/llms.txt Illustrates the management of collection stores in AlwatrNitrobase, including creation, opening, adding items with explicit or auto-increment IDs, checking item existence, retrieving item data and metadata, updating, replacing, and removing items. It also shows how to iterate over all items and get their IDs. ```typescript import { AlwatrNitrobase, Region } from '@alwatr/nitrobase'; const nitrobase = new AlwatrNitrobase({ rootPath: './db', defaultChangeDebounce: 40 }); // Create new collection itrobase.newCollection({ name: 'posts', region: Region.PerUser, ownerId: 'user_123', schemaVer: 2 }); // Open collection const posts = await nitrobase.openCollection({ name: 'posts', region: Region.PerUser, ownerId: 'user_123' }); // Add items with explicit IDs posts.addItem('post-1', { title: 'Welcome to Nitrobase', content: 'This is my first post', tags: ['intro', 'database'] }); // Append item with auto-increment ID const newId = posts.appendItem({ title: 'Second Post', content: 'More content here', tags: ['tutorial'] }); console.log(`Created item: ${newId}`); // "1" // Check if item exists if (posts.hasItem('post-1')) { // Get item data const itemData = posts.getItemData('post-1'); console.log(itemData.title); // Get item metadata const itemMeta = posts.getItemMeta('post-1'); console.log(`Item rev: ${itemMeta.rev}, created: ${new Date(itemMeta.created)}`); } // Update item (partial merge) posts.mergeItemData('post-1', { tags: ['intro', 'database', 'getting-started'] }); // Replace item data completely posts.replaceItemData('post-1', { title: 'Updated Title', content: 'Completely new content', tags: [] }); // Iterate over all items for (const item of posts.items()) { console.log(`${item.meta.id}: ${item.data.title}`); } // Get all IDs const ids = posts.keys(); console.log(`Total items: ${ids.length}`); // Remove item posts.removeItem('post-1'); // Save immediately posts.saveImmediate(null); ``` -------------------------------- ### Create and Use a Collection in JavaScript Source: https://github.com/alwatr/nitrobase/blob/next/packages/nitrobase/README.md Demonstrates how to initialize Alwatr Nitrobase, create a new collection for posts, and add an item to it. It uses the `AlwatrNitrobase` class and defines collection properties like region and schema version. ```javascript import { AlwatrNitrobase, Region } from '@alwatr/nitrobase'; const alwatrStore = new AlwatrNitrobase({ rootPath: './db', defaultChangeDebounce: 2_000, }); const postsCollectionId = { name: 'post', region: Region.PerUser, ownerId: 'user_123', schemaVer: 2, }; alwatrStore.newCollection(postsCollectionId); const postsCollection = await alwatrStore.openCollection(postsCollectionId); postsCollection.addItem('post1', { title: 'My First Post', content: 'This is the content of my first post.' }); ``` -------------------------------- ### Initialize AlwatrNitrobase Engine Source: https://context7.com/alwatr/nitrobase/llms.txt Initializes the AlwatrNitrobase engine, configuring the root database path, default change debounce time, and error handling for uninitialized states. It also provides methods to check for store existence, list all available stores, and manually save all pending changes. ```typescript import { AlwatrNitrobase, Region } from '@alwatr/nitrobase'; const nitrobase = new AlwatrNitrobase({ rootPath: './db', defaultChangeDebounce: 2000, errorWhenNotInitialized: false }); // Check if store exists const exists = nitrobase.hasStore({ name: 'products', region: Region.Public }); // List all stores const storeList = nitrobase.getStoreList(); for (const store of storeList) { console.log(`${store.meta.id}: type=${store.data.type}, region=${store.data.region}`); } // Save all pending changes await nitrobase.saveAll(); ``` -------------------------------- ### Create and Manage Documents with AlwatrNitrobase Source: https://context7.com/alwatr/nitrobase/llms.txt Demonstrates the creation, opening, reading, updating, and deletion of single-object stores (documents) in AlwatrNitrobase. It covers partial merging and full replacement of document data, accessing store metadata, manual saving, and unloading stores from memory. ```typescript import { AlwatrNitrobase, Region } from '@alwatr/nitrobase'; const nitrobase = new AlwatrNitrobase({ rootPath: './db' }); // Create new document itrobase.newDocument( { name: 'config/site', region: Region.Authenticated, schemaVer: 1 }, { siteName: 'My Site', theme: 'dark', maxUsers: 100 } ); // Open and read document const config = await nitrobase.openDocument({ name: 'config/site', region: Region.Authenticated }); const data = config.getData(); console.log(data.siteName); // "My Site" // Update document (partial merge) config.mergeData({ theme: 'light' }); // Replace document data config.replaceData({ siteName: 'New Site', theme: 'auto', maxUsers: 200 }); // Get metadata const meta = config.getStoreMeta(); console.log(`Rev: ${meta.rev}, Updated: ${new Date(meta.updated)}`); // Manual save (bypass debounce) config.saveImmediate(); // Unload from memory itrobase.unloadStore({ name: 'config/site', region: Region.Authenticated }); // Delete permanently await nitrobase.removeStore({ name: 'config/site', region: Region.Authenticated }); ``` -------------------------------- ### Schema Versioning and Migration in TypeScript Source: https://context7.com/alwatr/nitrobase/llms.txt Illustrates how to manage schema versions for data evolution in Alwatr Nitrobase. This includes creating stores with an initial schema version, opening existing stores, checking the current schema version, performing data migrations when schema changes, and updating the schema version. It also shows how to use `migrateName` for more complex migration scenarios. ```typescript import { AlwatrNitrobase, Region } from '@alwatr/nitrobase'; const nitrobase = new AlwatrNitrobase({ rootPath: './db' }); // Create store with schema version nitrobase.newCollection({ name: 'users', region: Region.Managers, schemaVer: 1 }); const users = await nitrobase.openCollection({ name: 'users', region: Region.Managers }); // Check current schema version console.log(`Current schema: v${users.schemaVer}`); // Migrate data when schema changes if (users.schemaVer === 1) { // Perform migration for (const user of users.items()) { if (!user.data.email) { users.mergeItemData(user.meta.id, { email: '' }); } } // Update schema version users.schemaVer = 2; users.saveImmediate(null); } // Use metadata migrateName for complex migrations nitrobase.newDocument( { name: 'config', region: Region.Secret, schemaVer: 3, migrateName: 'config-v3-migration' }, { version: 3, settings: {} } ); ``` -------------------------------- ### Create and Open a Document in JavaScript Source: https://github.com/alwatr/nitrobase/blob/next/packages/nitrobase/README.md Illustrates the process of creating a new document within Nitrobase and then opening it for access. This code defines a document ID with a specific region and provides initial data for the document. ```javascript import { AlwatrNitrobase, Region } from '@alwatr/nitrobase'; const alwatrStore = new AlwatrNitrobase({ rootPath: './db', defaultChangeDebounce: 2_000, }); const docId = { name: 'posts/my-first-post', region: Region.Authenticated, }; alwatrStore.newDocument(docId, { title: 'My First Post', content: 'This is the content of my first post.' }); const myPost = await alwatrStore.openDocument(docId); ``` -------------------------------- ### Manage Users with NitrobaseUserManagement Source: https://context7.com/alwatr/nitrobase/llms.txt Handles user authentication and multi-tenant user data. It allows creating, verifying, and retrieving user profiles and metadata. Requires Nitrobase instance and defines a UserProfile interface for data structure. ```typescript import { NitrobaseUserManagement, AlwatrNitrobase, Region } from '@alwatr/nitrobase'; const nitrobase = new AlwatrNitrobase({ rootPath: './db' }); // Initialize user management (creates user-list collection) await NitrobaseUserManagement.initialize(nitrobase); // Create user management instance interface UserProfile { name: string; email: string; role: string; settings: Record; } const userMgmt = new NitrobaseUserManagement(nitrobase); // Create new user await userMgmt.newUser({ userId: 'user_alice', userToken: 'tok_abc123xyz789', isManager: true, data: { name: 'Alice Smith', email: 'alice@example.com', role: 'admin', settings: { theme: 'dark' } } }); // Check if user exists const exists = await userMgmt.hasUser('user_alice'); console.log(`User exists: ${exists}`); // Verify user token const isValid = await userMgmt.verifyUserToken('user_alice', 'tok_abc123xyz789'); if (isValid) { // Get user data const profile = await userMgmt.getUserData('user_alice'); console.log(`Welcome, ${profile.name}!`); // Get user metadata const meta = await userMgmt.getUserMeta('user_alice'); console.log(`Account created: ${new Date(meta.created).toISOString()}`); } // Get user directory path const userDir = await userMgmt.getUserDirectory('user_alice'); console.log(`User data stored in: ${userDir}`); // Iterate all users const userIdGenerator = await userMgmt.userIds(); for (const userId of userIdGenerator) { const userData = await userMgmt.getUserData(userId); console.log(`${userId}: ${userData.email}`); } // Save user data changes userMgmt.save('user_alice'); // Force immediate save userMgmt.saveImmediate('user_alice'); ``` -------------------------------- ### NitrobaseUserManagement API Source: https://github.com/alwatr/nitrobase/blob/next/packages/user-management/README.md This section details the methods available within the NitrobaseUserManagement class for managing users. ```APIDOC ## NitrobaseUserManagement API ### Description This section details the methods available within the NitrobaseUserManagement class for managing users, including initialization, creation, retrieval, authentication, and data persistence. ### Methods #### Static Methods ##### `initialize(nitrobase: AlwatrNitrobase): Promise` * **Description:** Initializes the user management module. Must be called before creating a `NitrobaseUserManagement` instance. * **Method:** `POST` (Conceptual - this is a static initialization method, not a direct HTTP endpoint) * **Endpoint:** N/A #### Instance Methods ##### `newUser(user: NewUser): Promise` * **Description:** Creates a new user with the provided data and token. Sets up necessary storage and metadata. * **Method:** `POST` * **Endpoint:** `/users` (Conceptual) * **Parameters:** * **Request Body:** * **`user`** (NewUser) - Required - The data for the new user, including `userId`, `userToken`, and `data`. ##### `hasUser(userId: string): Promise` * **Description:** Checks if a user with the given ID exists. * **Method:** `GET` * **Endpoint:** `/users/{userId}/exists` (Conceptual) * **Parameters:** * **Path Parameters:** * **`userId`** (string) - Required - The ID of the user to check. ##### `getUserData(userId: string): Promise` * **Description:** Retrieves the data associated with the given user ID. * **Method:** `GET` * **Endpoint:** `/users/{userId}/data` (Conceptual) * **Parameters:** * **Path Parameters:** * **`userId`** (string) - Required - The ID of the user whose data to retrieve. ##### `getUserMeta(userId: string): Promise>` * **Description:** Retrieves metadata about the user's stored information. * **Method:** `GET` * **Endpoint:** `/users/{userId}/meta` (Conceptual) * **Parameters:** * **Path Parameters:** * **`userId`** (string) - Required - The ID of the user whose metadata to retrieve. ##### `verifyUserToken(userId: string, token: string): Promise` * **Description:** Verifies the provided token against the stored token for the user. * **Method:** `POST` * **Endpoint:** `/users/{userId}/verify-token` (Conceptual) * **Parameters:** * **Path Parameters:** * **`userId`** (string) - Required - The ID of the user. * **Request Body:** * **`token`** (string) - Required - The token to verify. ##### `save(userId: string): void` * **Description:** Saves any changes to the user's data. This operation is non-blocking. * **Method:** `PUT` (Conceptual) * **Endpoint:** `/users/{userId}/save` (Conceptual) * **Parameters:** * **Path Parameters:** * **`userId`** (string) - Required - The ID of the user whose data to save. ##### `saveImmediate(userId: string): void` * **Description:** Immediately saves changes to the user's data. This operation is blocking. * **Method:** `PUT` (Conceptual) * **Endpoint:** `/users/{userId}/save-immediate` (Conceptual) * **Parameters:** * **Path Parameters:** * **`userId`** (string) - Required - The ID of the user whose data to save immediately. ##### `userIds(): Promise>` * **Description:** Returns an asynchronous generator that yields all user IDs. * **Method:** `GET` * **Endpoint:** `/users/ids` (Conceptual) ##### `getUserDirectory(userId: string): Promise` * **Description:** Retrieves the file system directory associated with the user. * **Method:** `GET` * **Endpoint:** `/users/{userId}/directory` (Conceptual) * **Parameters:** * **Path Parameters:** * **`userId`** (string) - Required - The ID of the user whose directory to retrieve. ``` -------------------------------- ### Organizing Data with Regions and Multi-Tenancy in TypeScript Source: https://context7.com/alwatr/nitrobase/llms.txt Demonstrates how to organize data stores (collections and documents) using different regions for multi-tenant applications. Regions like Public, Authenticated, Managers, PerUser, PerOwner, and Secret define access levels and data isolation. File paths are automatically organized based on the region and owner ID. ```typescript import { AlwatrNitrobase, Region } from '@alwatr/nitrobase'; const nitrobase = new AlwatrNitrobase({ rootPath: './db' }); // Public data (accessible to anyone) nitrobase.newCollection({ name: 'products', region: Region.Public }); // Authenticated users only nitrobase.newDocument( { name: 'price-list', region: Region.Authenticated }, { currency: 'USD', items: {} } ); // Manager/admin access only nitrobase.newCollection({ name: 'user-list', region: Region.Managers }); // Per-user stores (isolated by user ID) nitrobase.newCollection({ name: 'orders', region: Region.PerUser, ownerId: 'user_456' }); // Per-owner stores (isolated by custom owner ID) nitrobase.newDocument( { name: 'device-settings', region: Region.PerOwner, ownerId: 'device_789' }, { brightness: 80, volume: 50 } ); // Secret/private stores (not publicly accessible) nitrobase.newDocument( { name: 'api-keys', region: Region.Secret }, { openai: 'sk-...', stripe: 'sk_test_...' } ); // File paths are automatically organized: // - Public: p/products.col.asj // - Authenticated: a/price-list.doc.asj // - PerUser: u/use/user_456/orders.col.asj // - Secret: .s/api-keys.doc.asj ``` -------------------------------- ### Generate Store ID and Path with Nitrobase Helper Functions Source: https://context7.com/alwatr/nitrobase/llms.txt This snippet demonstrates the usage of `getStoreId` and `getStorePath` functions from '@alwatr/nitrobase' to generate unique store identifiers and file system paths. These functions handle different regions (Public, PerUser, PerOwner) and store types (Collection, Document), simplifying data organization and access. The generated paths often include owner ID prefixes for sharding purposes. ```typescript import { getStoreId, getStorePath, Region, StoreFileType, StoreFileExtension } from '@alwatr/nitrobase'; // Generate store ID string const id1 = getStoreId({ name: 'products', region: Region.Public }); console.log(id1); // "p/products" const id2 = getStoreId({ name: 'orders', region: Region.PerUser, ownerId: 'user_123' }); console.log(id2); // "u/orders/user_123" // Generate file system path const path1 = getStorePath({ name: 'products', region: Region.Public, type: StoreFileType.Collection, extension: StoreFileExtension.Json }); console.log(path1); // "p/products.col.asj" const path2 = getStorePath({ name: 'profile', region: Region.PerUser, ownerId: 'user_abc', type: StoreFileType.Document, extension: StoreFileExtension.Json }); console.log(path2); // "u/use/user_abc/profile.doc.asj" // Path includes owner ID prefix for sharding const path3 = getStorePath({ name: 'settings', region: Region.PerOwner, ownerId: 'device_xyz123', type: StoreFileType.Document }); console.log(path3); // "o/xyz/device_xyz123/settings.doc.asj" ``` -------------------------------- ### Managing Extra Metadata in TypeScript Source: https://context7.com/alwatr/nitrobase/llms.txt Explains how to store and manage custom metadata alongside documents and collections in Alwatr Nitrobase. This includes creating documents and collections, opening them, setting and merging extra metadata using `replaceExtraMeta` and `mergeExtraMeta`, and retrieving it with `getExtraMeta`. This is useful for storing auxiliary information like timestamps, configuration options, or usage statistics. ```typescript import { AlwatrNitrobase, Region } from '@alwatr/nitrobase'; const nitrobase = new AlwatrNitrobase({ rootPath: './db' }); nitrobase.newDocument( { name: 'analytics', region: Region.Secret }, { pageViews: 0, visitors: 0 } ); const analytics = await nitrobase.openDocument({ name: 'analytics', region: Region.Secret }); // Set extra metadata (custom fields in meta.extra) analytics.replaceExtraMeta({ lastReset: Date.now(), resetInterval: 86400000, dataRetention: 30 }); // Merge into existing extra metadata analytics.mergeExtraMeta({ apiVersion: '2.0', exportFormat: 'json' }); // Read extra metadata interface AnalyticsExtra { lastReset: number; resetInterval: number; dataRetention: number; apiVersion: string; exportFormat: string; } const extra = analytics.getExtraMeta(); console.log(`Last reset: ${new Date(extra.lastReset)}`); console.log(`Data retention: ${extra.dataRetention} days`); // Collections also support extra metadata nitrobase.newCollection({ name: 'tasks', region: Region.PerUser, ownerId: 'user_999' }); const tasks = await nitrobase.openCollection({ name: 'tasks', region: Region.PerUser, ownerId: 'user_999' }); tasks.replaceExtraMeta({ totalTasks: 0, completedTasks: 0, category: 'work' }); ``` -------------------------------- ### Perform Advanced Collection Operations Source: https://context7.com/alwatr/nitrobase/llms.txt Enables memory-efficient iteration over large collections using generators. Supports creating, opening, appending items, iterating IDs, accessing values, and direct context manipulation. Includes options for freezing collections to prevent saves. ```typescript import { AlwatrNitrobase, Region } from '@alwatr/nitrobase'; const nitrobase = new AlwatrNitrobase({ rootPath: './db' }); nitrobase.newCollection({ name: 'logs', region: Region.Secret }); const logs = await nitrobase.openCollection({ name: 'logs', region: Region.Secret }); // Add many items for (let i = 0; i < 10000; i++) { logs.appendItem({ timestamp: Date.now(), level: 'info', message: `Log entry ${i}` }); } // Use generator for memory-efficient iteration (large collections) for (const id of logs.ids()) { const item = logs.getItemData(id); if (item.level === 'error') { console.log(`Error found: ${item.message}`); } } // Use values() for array access (small collections) const allItems = logs.values(); console.log(`Total items: ${allItems.length}`); // Direct context access (use with caution) const itemContext = logs.getItemContext_('1'); if (itemContext) { console.log(`Direct access: ${itemContext.data.message}`); // Can mutate directly, but must call save() itemContext.data.processed = true; logs.save(null); } // Freeze collection (prevent saves) logs.freeze = true; logs.addItem('test', { message: 'test' }); // Change made but won't save console.log(`Is frozen: ${logs.freeze}`); logs.freeze = false; // Re-enable saves ``` -------------------------------- ### Inspect Store Metadata Source: https://context7.com/alwatr/nitrobase/llms.txt Provides access to comprehensive metadata for stores (documents and collections) for debugging and monitoring purposes. This includes details like store ID, file path, type, region, schema version, creation/update timestamps, and debounce settings. ```typescript import { AlwatrNitrobase, Region } from '@alwatr/nitrobase'; const nitrobase = new AlwatrNitrobase({ rootPath: './db' }); nitrobase.newDocument( { name: 'app-state', region: Region.Secret, schemaVer: 1, changeDebounce: 1000 }, { isRunning: true } ); const appState = await nitrobase.openDocument({ name: 'app-state', region: Region.Secret }); // Get full metadata const meta = appState.getStoreMeta(); console.log(`Store ID: ${appState.id}`); console.log(`File path: ${appState.path}`); console.log(`Type: ${meta.type}`); console.log(`Region: ${meta.region}`); console.log(`Schema version: ${meta.schemaVer}`); console.log(`File format version: ${meta.fv}`); console.log(`Revision: ${meta.rev}`); console.log(`Created: ${new Date(meta.created).toISOString()}`); console.log(`Updated: ${new Date(meta.updated).toISOString()}`); console.log(`Debounce: ${meta.changeDebounce}ms`); console.log(`Extension: ${meta.extension}`); // Check for unsaved changes console.log(`Has changes: ${appState.hasUnprocessedChanges_}`); // Get full context (includes meta + data) const context = appState.getFullContext_(); console.log(`OK status: ${context.ok}`); console.log(`Data keys: ${Object.keys(context.data).join(', ')}`); // Collection metadata includes lastAutoId nitrobase.newCollection({ name: 'items', region: Region.Public }); const items = await nitrobase.openCollection({ name: 'items', region: Region.Public }); items.appendItem({ value: 'a' }); items.appendItem({ value: 'b' }); const itemsMeta = items.getStoreMeta(); console.log(`Last auto ID: ${itemsMeta.lastAutoId}`); // 2 ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.