The main database class that provides cross-platform database functionality.
new UnifiedDB(config?, options?)Parameters:
config(Object, optional): Database configuration objectoptions(Object, optional): Database options
Options:
autoInit(boolean, default: true): Automatically initialize the databasestorageType(string, default: 'auto'): Force specific storage backendstorage(Object): Storage backend specific options
Initialize the database and storage backend.
await db.init()Returns: Promise<void>
Create a new record in the specified model.
const user = await db.create('User', {
name: 'John Doe',
email: 'john@example.com'
})Parameters:
modelName(string): Name of the modeldata(Object): Data to create
Returns: Promise<Object> - Created record
Find a single record matching the criteria.
const user = await db.findUnique('User', { id: 'user123' })Parameters:
modelName(string): Name of the modelwhere(Object): Search criteria
Returns: Promise<Object|null> - Found record or null
Update a record matching the criteria.
const updatedUser = await db.update('User',
{ id: 'user123' },
{ name: 'Jane Doe' }
)Parameters:
modelName(string): Name of the modelwhere(Object): Search criteriadata(Object): Update data
Returns: Promise<Object|null> - Updated record or null
Update multiple records matching the criteria.
const updatedUsers = await db.updateMany('User',
{ active: false },
{ status: 'inactive' }
)Parameters:
modelName(string): Name of the modelwhere(Object): Search criteriadata(Object): Update data
Returns: Promise<Array> - Array of updated records
Delete a record matching the criteria.
const deletedUser = await db.delete('User', { id: 'user123' })Parameters:
modelName(string): Name of the modelwhere(Object): Search criteria
Returns: Promise<Object|null> - Deleted record or null
Delete multiple records matching the criteria.
const deletedUsers = await db.deleteMany('User', { active: false })Parameters:
modelName(string): Name of the modelwhere(Object): Search criteria
Returns: Promise<Array> - Array of deleted records
Add a hook for database operations.
db.addHook('beforeCreate', (modelName, data) => {
console.log(`Creating ${modelName}:`, data)
return data
})Parameters:
hookName(string): Hook name ('beforeCreate', 'afterCreate', etc.)hookFunction(Function): Hook function
Clear all data from the database.
await db.clearAll()Returns: Promise<void>
Export all database data.
const backup = await db.export()Returns: Promise<Object> - Database export
Import data into the database.
await db.import(backup, { clearFirst: true })Parameters:
data(Object): Data to importoptions(Object, optional): Import optionsclearFirst(boolean): Clear database before importvalidateConfig(boolean): Validate configuration compatibility
Returns: Promise<void>
Get database statistics.
const stats = await db.getStats()Returns: Promise<Object> - Database statistics
Close the database connection.
await db.close()Returns: Promise<void>
const config = {
models: {
User: {
fields: {
id: { type: 'string', primaryKey: true },
name: { type: 'string', required: true },
email: { type: 'string', unique: true },
age: { type: 'number', default: 0 },
createdAt: { type: 'date', default: 'now' }
}
}
},
settings: {
autoId: true,
timestamps: true,
validation: true,
encryption: false
},
version: '1.0.0'
}string: Text datanumber: Numeric databoolean: True/false valuesdate: Date/time valuesarray: Array dataobject: Object data
primaryKey(boolean): Mark as primary keyrequired(boolean): Field is requiredunique(boolean): Field must be uniquedefault(any|Function): Default value or functionvalidate(Function): Custom validation function
autoId(boolean): Automatically generate IDstimestamps(boolean): Add createdAt/updatedAt fieldsvalidation(boolean): Enable data validationencryption(boolean): Enable data encryption
Model clients provide a Prisma-like API for each model.
// Access model client
const userClient = db.user // or db.User
// Create
const user = await db.user.create({ name: 'John' })
// Find unique
const user = await db.user.findUnique({ id: 'user123' })
// Find many with query builder
const users = await db.user.findMany({
where: { age: { gte: 18 } },
orderBy: { name: 'asc' },
take: 10,
skip: 0
})
// Update
const user = await db.user.update(
{ id: 'user123' },
{ name: 'Jane' }
)
// Delete
const user = await db.user.delete({ id: 'user123' })
// Count
const count = await db.user.count({ active: true })Advanced query building with method chaining.
Add where conditions.
query.where('name', 'John')
query.where('age', '>', 18)
query.where('email', 'contains', '@gmail.com')Operators:
equals(default)notgt,gte,lt,ltecontains,startsWith,endsWithin,notInisNull,isNotNullisEmpty,isNotEmptyregex
Add ordering.
query.orderBy('name', 'asc')
query.orderBy('createdAt', 'desc')Limit results.
query.limit(10)
query.take(10) // Prisma-style aliasSkip results.
query.offset(20)
query.skip(20) // Prisma-style aliasSelect specific fields.
query.select(['name', 'email'])
query.select({ name: true, email: true })Include related data.
query.include('posts')
query.include({ posts: { where: { published: true } } })Execute query and return multiple results.
const users = await query.findMany()Execute query and return first result.
const user = await query.findFirst()Execute query expecting exactly one result.
const user = await query.findUnique()Count matching records.
const count = await query.count()Utility for detecting the runtime environment.
Detect current environment.
const env = EnvironmentDetector.detect()
// Returns: 'browser' | 'node' | 'electron' | 'react-native' | 'unknown'Check if running in specific environment.
const isBrowser = EnvironmentDetector.is('browser')Get environment capabilities.
const capabilities = EnvironmentDetector.getCapabilities()
// Returns object with capability flagsBrowser localStorage implementation.
Environment: Browser
Capacity: ~5-10MB
Persistence: Until cleared by user
Browser IndexedDB implementation.
Environment: Browser
Capacity: ~50MB+ (quota-based)
Persistence: Until cleared by user
Node.js/Electron file system implementation.
Environment: Node.js, Electron
Capacity: Disk space limited
Persistence: Permanent
React Native AsyncStorage implementation.
Environment: React Native
Capacity: Platform dependent
Persistence: Until app uninstalled
All async methods can throw errors. Always use try-catch:
try {
const user = await db.user.create({ name: 'John' })
} catch (error) {
console.error('Database error:', error.message)
}Available hooks for extending functionality:
beforeCreate- Before creating recordsafterCreate- After creating recordsbeforeUpdate- Before updating recordsafterUpdate- After updating recordsbeforeDelete- Before deleting recordsafterDelete- After deleting records
db.addHook('beforeCreate', async (modelName, data) => {
// Modify data before creation
data.createdBy = getCurrentUser()
return data
})