CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-lokijs

Fast document oriented javascript in-memory database

Pending
Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

SecuritybySnyk

Pending

The risk profile of this skill

Overview
Eval results
Files

database-management.mddocs/

Database Management

Core database operations for creating, configuring, and managing LokiJS database instances with persistence and serialization capabilities.

Capabilities

Database Constructor

Creates a new LokiJS database instance with optional configuration.

/**
 * Creates a new LokiJS database instance
 * @param filename - Optional filename for persistence
 * @param options - Database configuration options
 */
constructor Loki(filename?: string, options?: DatabaseOptions);

interface DatabaseOptions {
  /** Enable automatic saving at intervals */
  autosave?: boolean;
  /** Autosave interval in milliseconds */
  autosaveInterval?: number;
  /** Persistence adapter for storage operations */
  adapter?: PersistenceAdapter;
  /** Serialization method ('normal', 'pretty', 'destructured') */
  serializationMethod?: string;
  /** Delimiter for destructured serialization */
  destructureDelimiter?: string;
  /** Enable verbose logging */
  verbose?: boolean;
  /** Throttled saves configuration */
  throttledSaves?: boolean;
}

Usage Examples:

// Basic database
const db = new loki();

// Database with filename
const db = new loki('myapp.db');

// Database with options
const db = new loki('myapp.db', {
  autosave: true,
  autosaveInterval: 4000,
  adapter: new loki.LokiFsAdapter(),
  verbose: true
});

Collection Management

Add, retrieve, and manage collections within the database.

/**
 * Add a collection to the database
 * @param name - Collection name
 * @param options - Collection configuration options
 * @returns The created collection
 */
addCollection(name: string, options?: CollectionOptions): Collection;

/**
 * Retrieve a collection by name
 * @param collectionName - Name of the collection
 * @returns Collection instance or null if not found
 */
getCollection(collectionName: string): Collection | null;

/**
 * Remove a collection from the database
 * @param collectionName - Name of collection to remove
 */
removeCollection(collectionName: string): void;

/**
 * Rename an existing collection
 * @param oldName - Current collection name
 * @param newName - New collection name
 */
renameCollection(oldName: string, newName: string): void;

/**
 * Get list of all collection names
 * @returns Array of collection names
 */
listCollections(): string[];

Usage Examples:

// Add collections
const users = db.addCollection('users');
const orders = db.addCollection('orders', {
  unique: ['orderId'],
  indices: ['customerId']
});

// Get existing collection
const users = db.getCollection('users');

// List all collections
const collections = db.listCollections();
console.log(collections); // ['users', 'orders']

// Rename collection
db.renameCollection('users', 'customers');

// Remove collection
db.removeCollection('orders');

Database Persistence

Load and save database state using configured persistence adapters.

/**
 * Load database from storage
 * @param options - Load options
 * @param callback - Completion callback
 */
loadDatabase(options?: any, callback?: (err?: Error) => void): void;

/**
 * Save database to storage
 * @param callback - Completion callback
 */
saveDatabase(callback?: (err?: Error) => void): void;

/**
 * Delete database from storage
 * @param options - Delete options
 * @param callback - Completion callback
 */
deleteDatabase(options?: any, callback?: (err?: Error) => void): void;

Usage Examples:

// Load database
db.loadDatabase({}, (err) => {
  if (err) {
    console.error('Failed to load database:', err);
  } else {
    console.log('Database loaded successfully');
  }
});

// Save database
db.saveDatabase((err) => {
  if (err) {
    console.error('Failed to save database:', err);
  } else {
    console.log('Database saved successfully');
  }
});

// Delete database
db.deleteDatabase({}, (err) => {
  if (err) {
    console.error('Failed to delete database:', err);
  } else {
    console.log('Database deleted successfully');
  }
});

Serialization

Convert database to and from JSON for storage or transport.

/**
 * Serialize database to JSON string
 * @param options - Serialization options
 * @returns JSON string representation
 */
serialize(options?: SerializeOptions): string;

/**
 * Serialize using destructured format
 * @param options - Serialization options
 * @returns Destructured JSON representation
 */
serializeDestructured(options?: SerializeOptions): string;

/**
 * Load database from JSON string
 * @param serializedDb - JSON string of database
 * @param options - Load options
 */
loadJSON(serializedDb: string, options?: any): void;

/**
 * Load database from JSON object
 * @param dbObject - Database object
 * @param options - Load options
 */
loadJSONObject(dbObject: object, options?: any): void;

interface SerializeOptions {
  /** Serialization method ('normal', 'pretty', 'destructured') */
  serializationMethod?: string;
  /** Delimiter for destructured serialization */
  destructureDelimiter?: string;
  /** Collections to include in serialization */
  partitioned?: boolean;
}

Usage Examples:

// Serialize database
const jsonString = db.serialize();

// Serialize with pretty formatting
const prettyJson = db.serialize({
  serializationMethod: 'pretty'
});

// Load from JSON string
const newDb = new loki();
newDb.loadJSON(jsonString);

// Load from object
const dbObject = JSON.parse(jsonString);
newDb.loadJSONObject(dbObject);

Auto-save Configuration

Configure automatic database persistence at regular intervals.

/**
 * Enable auto-save functionality
 * @param options - Auto-save configuration
 * @param callback - Save completion callback
 */
autosaveEnable(options?: AutosaveOptions, callback?: Function): void;

/**
 * Disable auto-save functionality
 */
autosaveDisable(): void;

/**
 * Check if auto-save is needed
 * @returns True if database needs saving
 */
autosaveDirty(): boolean;

interface AutosaveOptions {
  /** Auto-save interval in milliseconds */
  autosaveInterval?: number;
  /** Save callback function */
  saveCallback?: Function;
}

Usage Examples:

// Enable auto-save every 5 seconds
db.autosaveEnable({
  autosaveInterval: 5000,
  saveCallback: (err) => {
    if (err) {
      console.error('Auto-save failed:', err);
    }
  }
});

// Check if save is needed
if (db.autosaveDirty()) {
  console.log('Database has unsaved changes');
}

// Disable auto-save
db.autosaveDisable();

Database Information

Retrieve metadata and configuration information about the database.

/**
 * Get database name
 * @returns Database filename
 */
getName(): string;

/**
 * Create a copy of the database
 * @param options - Copy options
 * @returns New database instance
 */
copy(options?: any): Loki;

/**
 * Close the database
 * @param callback - Close completion callback
 */
close(callback?: Function): void;

Usage Examples:

// Get database name
const name = db.getName();
console.log('Database name:', name);

// Create database copy
const dbCopy = db.copy();

// Close database
db.close(() => {
  console.log('Database closed');
});

Changes API

Track and manage document changes across collections.

/**
 * Generate changes notification for specified collections
 * @param arrayOfCollectionNames - Array of collection names to generate changes for
 * @returns Object containing changes data
 */
generateChangesNotification(arrayOfCollectionNames: string[]): object;

/**
 * Serialize changes for specified collections to JSON string
 * @param collectionNamesArray - Array of collection names
 * @returns JSON string of changes
 */
serializeChanges(collectionNamesArray: string[]): string;

/**
 * Clear all changes in all collections
 */
clearChanges(): void;

Usage Examples:

// Enable changes tracking when creating collections
const users = db.addCollection('users', {
  disableChangesApi: false
});

// Make some changes
users.insert({ name: 'Alice', age: 25 });
users.insert({ name: 'Bob', age: 30 });

// Get changes for specific collections
const changes = db.generateChangesNotification(['users']);
console.log('Changes:', changes);

// Serialize changes to JSON
const changesJson = db.serializeChanges(['users']);

// Clear all changes
db.clearChanges();

Advanced Serialization

Specialized serialization methods for different use cases.

/**
 * Serialize database using destructured format
 * @param options - Destructured serialization options
 * @returns Destructured representation
 */
serializeDestructured(options?: DestructuredOptions): string | any[];

/**
 * Serialize individual collection
 * @param options - Collection serialization options
 * @returns Serialized collection data
 */
serializeCollection(options: CollectionSerializeOptions): string | any[];

/**
 * Deserialize destructured database format
 * @param destructuredSource - Destructured data source
 * @param options - Deserialization options
 * @returns Database object representation
 */
deserializeDestructured(destructuredSource: any, options?: any): object;

/**
 * Deserialize individual collection data
 * @param destructuredSource - Collection data source
 * @param options - Deserialization options
 * @returns Array of documents
 */
deserializeCollection(destructuredSource: any, options?: any): object[];

/**
 * Alias for serialize method
 * @param options - Serialization options
 * @returns JSON string representation
 */
toJson(options?: SerializeOptions): string;

interface DestructuredOptions {
  /** Enable delimited format */
  delimited?: boolean;
  /** Custom delimiter string */
  delimiter?: string;
  /** Enable partitioned format */
  partitioned?: boolean;
  /** Specific partition to serialize */
  partition?: number;
}

interface CollectionSerializeOptions {
  /** Enable delimited format */
  delimited?: boolean;
  /** Custom delimiter string */
  delimiter?: string;
  /** Collection index to serialize */
  collectionIndex: number;
}

Usage Examples:

// Destructured serialization for large databases
const destructured = db.serializeDestructured({
  delimited: true,
  delimiter: '|'
});

// Serialize individual collection
const collectionData = db.serializeCollection({
  collectionIndex: 0,
  delimited: true
});

// Use toJson alias
const jsonString = db.toJson({ serializationMethod: 'pretty' });

// Deserialize destructured format
const dbObject = db.deserializeDestructured(destructured);
const newDb = new loki();
newDb.loadJSONObject(dbObject);

Internal Methods

Low-level methods for advanced usage and adapter development.

/**
 * Load collection object into database
 * @param collection - Collection object to load
 */
loadCollection(collection: object): void;

/**
 * Configure database options
 * @param options - Configuration options
 * @param initialConfig - Whether this is initial configuration
 */
configureOptions(options: DatabaseOptions, initialConfig?: boolean): void;

/**
 * Get indexed adapter for browserify compatibility
 * @returns Indexed adapter if available
 */
getIndexedAdapter(): any;

/**
 * Internal serialization replacer function
 * @param key - Property key
 * @param value - Property value
 * @returns Modified value or undefined to exclude
 */
serializeReplacer(key: string, value: any): any;

/**
 * Internal save method without throttling
 * @param callback - Completion callback
 */
saveDatabaseInternal(callback?: (err?: Error) => void): void;

/**
 * Internal load method without throttling
 * @param options - Load options
 * @param callback - Completion callback
 */
loadDatabaseInternal(options?: any, callback?: (err?: Error) => void): void;

/**
 * Drain throttled save queue
 * @param callback - Completion callback
 * @param options - Drain options
 */
throttledSaveDrain(callback: Function, options?: object): void;

/**
 * Clear autosave flags after successful save
 */
autosaveClearFlags(): void;

Usage Examples:

// These methods are primarily for internal use
// Most applications should use the higher-level methods instead

// Example: Custom adapter development might use internal methods
db.saveDatabaseInternal((err) => {
  if (err) {
    console.error('Internal save failed:', err);
  }
});

Properties

interface Loki {
  /** Database filename */
  filename: string;
  /** Array of collections */
  collections: Collection[];
  /** Database version */
  databaseVersion: number;
  /** Engine version */
  engineVersion: number;
  /** Auto-save enabled flag */
  autosave: boolean;
  /** Auto-save interval in milliseconds */
  autosaveInterval: number;
  /** Database options */
  options: DatabaseOptions;
  /** Persistence adapter instance */
  persistenceAdapter: PersistenceAdapter;
  /** Verbose logging flag */
  verbose: boolean;
}

docs

advanced-querying.md

collection-operations.md

database-management.md

dynamic-views.md

index.md

persistence-adapters.md

tile.json