JavaScript in-memory database with SQL-like query capabilities for array manipulation
—
Core functionality for creating and managing TaffyDB database instances, including data insertion, merging, configuration, and persistence.
Creates a new TaffyDB database instance from an array of objects or JSON string.
/**
* Creates a new TaffyDB database instance
* @param data - Initial data as array of objects or JSON string (optional)
* @returns TaffyDatabase instance
*/
function TAFFY(data?: object[] | string): TaffyDatabase;Usage Examples:
const TAFFY = require('taffydb').taffy;
// Create empty database
const emptyDB = TAFFY();
// Create database with initial data
const products = TAFFY([
{ id: 1, name: "Laptop", price: 999.99 },
{ id: 2, name: "Mouse", price: 29.99 }
]);
// Create database from JSON string
const jsonData = '[{"name":"Alice","age":30},{"name":"Bob","age":25}]';
const users = TAFFY(jsonData);Add new records to the database with automatic ID assignment and template merging.
/**
* Insert new records into the database
* @param records - Single object, array of objects, or JSON string
* @returns QueryResult containing inserted records
*/
insert(records: object | object[] | string): QueryResult;Usage Examples:
// Insert single record
const result = db.insert({ name: "Charlie", age: 35 });
// Insert multiple records
db.insert([
{ name: "David", age: 40 },
{ name: "Eve", age: 28 }
]);
// Insert from JSON string
db.insert('{"name":"Frank","age":45}');
// Insert with array format (first row as headers)
db.insert([
["name", "age", "city"],
["Grace", 32, "New York"],
["Henry", 27, "Boston"]
]);Insert or update records based on a key field, enabling upsert functionality.
/**
* Insert or update records based on key field matching
* @param records - Array of objects to merge
* @param key - Field name to match on (default: 'id')
* @param runEvent - Whether to trigger event callbacks (default: false)
* @returns QueryResult containing affected records
*/
merge(records: object[], key?: string, runEvent?: boolean): QueryResult;Usage Examples:
// Merge based on 'id' field (default)
db.merge([
{ id: 1, name: "Updated Product", price: 899.99 }, // Update existing
{ id: 3, name: "New Product", price: 199.99 } // Insert new
]);
// Merge based on custom key field
db.merge([
{ email: "alice@example.com", name: "Alice Smith", active: true },
{ email: "bob@example.com", name: "Bob Jones", active: false }
], "email");
// Merge with event callbacks enabled
db.merge(newRecords, "id", true);Change the default sort order of records in the database, affecting subsequent operations.
/**
* Sort the database records and update internal indexes
* @param orderString - Sort specification (e.g., "name desc, age")
* @returns Boolean indicating success
*/
sort(orderString: string): boolean;Usage Examples:
// Sort by single field ascending
db.sort("name");
// Sort by single field descending
db.sort("price desc");
// Sort by multiple fields
db.sort("category, price desc");
// Logical sort (natural ordering for mixed strings/numbers)
db.sort("name logical");
// After sorting, queries return records in new order
const sortedResults = db().get(); // Returns records in sorted orderGet or set database configuration options including event callbacks and behavior settings.
/**
* Get or set database settings
* @param options - Configuration object (optional)
* @returns Current settings object
*/
settings(options?: DatabaseSettings): DatabaseSettings;
interface DatabaseSettings {
template?: object; // Default template for new records
onInsert?: (record: object) => void; // Insert event callback
onUpdate?: (newRecord: object, oldRecord: object, changes: object) => void;
onRemove?: (record: object) => void; // Remove event callback
onDBChange?: () => void; // General change callback
storageName?: string; // localStorage key name
forcePropertyCase?: 'lower' | 'upper' | null; // Force property name case
cacheSize?: number; // Query result cache size (default: 100)
name?: string; // Database name
}Usage Examples:
// Get current settings
const currentSettings = db.settings();
// Set template for new records
db.settings({
template: { active: true, created: new Date() }
});
// Set event callbacks
db.settings({
onInsert: function(record) {
console.log('Inserted:', record);
},
onUpdate: function(newRecord, oldRecord, changes) {
console.log('Updated:', changes);
},
onRemove: function(record) {
console.log('Removed:', record);
}
});
// Configure property case handling
db.settings({
forcePropertyCase: 'lower' // All property names converted to lowercase
});
// Set cache size for query optimization
db.settings({
cacheSize: 500 // Cache up to 500 query results
});Enable automatic persistence to browser localStorage with automatic saving on database changes.
/**
* Enable localStorage persistence for the database
* @param storageName - Key name for localStorage (optional)
* @returns TaffyDatabase instance for chaining
*/
store(storageName?: string): TaffyDatabase;Usage Examples:
// Enable localStorage with automatic key generation
db.store("myAppData");
// Database will automatically:
// - Load existing data from localStorage on initialization
// - Save changes to localStorage after modifications
// Data is stored in localStorage as:
// localStorage.getItem("taffy_myAppData")
// Check if data was loaded from storage
const db2 = TAFFY().store("existingData");
// Returns true if data was loaded from localStorageEvery TaffyDB instance has a TAFFY property for identification.
/**
* Database identification property
*/
TAFFY: boolean; // Always true for TaffyDB instancesUsage Examples:
// Check if object is a TaffyDB instance
function isTaffyDB(obj) {
return obj && obj.TAFFY === true;
}
// Conditional logic based on database type
if (myDB.TAFFY) {
// Handle TaffyDB instance
const results = myDB({ active: true });
} else {
// Handle regular array
const results = myDB.filter(item => item.active);
}Install with Tessl CLI
npx tessl i tessl/npm-taffydb