@tubox/client
v1.0.0
Published
MongoDB-like client library for Tubox database
Maintainers
Readme
Tubox Client for Node.js
MongoDB-like client library for Tubox database with TypeScript support.
Features
- 🚀 MongoDB-Compatible API - Familiar interface for NoSQL operations
- 🔄 Connection Pooling - Automatic connection reuse and management
- 💪 TypeScript Support - Full type definitions included
- 🔒 Transaction Support - ACID transactions with multiple isolation levels
- 📊 Metrics & Monitoring - Built-in performance tracking
- ⚡ Async/Await - Modern Promise-based API
- 🔐 Session Management - MongoDB-style sessions for transactions
- 🛡️ Error Handling - Comprehensive exception hierarchy
- 📝 Logging - Configurable logging levels
Installation
npm install @tubox/clientQuick Start
import { TuboxClient } from '@tubox/client';
async function main() {
// Create client
const client = new TuboxClient({
host: 'localhost',
port: 7188,
maxPoolSize: 10,
maxConnections: 100,
});
// Connect and authenticate
await client.connect();
await client.authenticate('[email protected]', 'password');
// Access database and collection
const db = client.database('mydb');
const users = db.collection('users');
// Insert document
const result = await users.insertOne({
name: 'Alice',
email: '[email protected]',
age: 30,
});
console.log('Inserted ID:', result.inserted_id);
// Find documents
const foundUsers = await users.find({ age: { $gte: 25 } });
console.log('Found users:', foundUsers.documents);
// Update document
await users.updateOne(
{ name: 'Alice' },
{ $set: { age: 31 } }
);
// Delete document
await users.deleteOne({ name: 'Alice' });
// Close connection
await client.close();
}
main().catch(console.error);MongoDB-Style API
Database Operations
// List databases
const databases = await client.listDatabases();
// Drop database
await client.dropDatabase('mydb');
// Rename database
await client.renameDatabase('oldname', 'newname');Collection Operations
const col = db.collection('users');
// Insert operations
await col.insertOne({ name: 'Bob' });
// Find operations
const users = await col.find({ age: { $gt: 25 } });
const user = await col.findOne({ name: 'Bob' });
// Update operations
await col.updateOne({ name: 'Bob' }, { $set: { age: 30 } });
await col.updateMany({ active: false }, { $set: { status: 'inactive' } });
// Delete operations
await col.deleteOne({ name: 'Bob' });
await col.deleteMany({ status: 'inactive' });
// Count documents
const count = await col.count({ age: { $gte: 18 } });
// Drop collection
await col.drop();
// Rename collection
await col.rename('new_users');Query Operators
Supports MongoDB query operators:
// Comparison operators
{ age: { $eq: 25 } }
{ age: { $gt: 25 } }
{ age: { $gte: 25 } }
{ age: { $lt: 40 } }
{ age: { $lte: 40 } }
{ age: { $ne: 25 } }
{ age: { $in: [25, 30, 35] } }
{ age: { $nin: [25, 30] } }
// Logical operators
{ $and: [{ age: { $gte: 25 } }, { age: { $lte: 40 } }] }
{ $or: [{ status: 'active' }, { status: 'pending' }] }
{ $not: { age: { $lt: 18 } } }
// Element operators
{ field: { $exists: true } }
{ field: { $type: 'string' } }
// String operators
{ name: { $regex: '^A' } }Update Operators
// Field update operators
{ $set: { field: value } }
{ $unset: { field: '' } }
{ $inc: { count: 1 } }
{ $mul: { price: 1.1 } }
{ $rename: { old_field: 'new_field' } }
{ $min: { score: 100 } }
{ $max: { score: 0 } }
{ $currentDate: { updated_at: true } }
// Array operators
{ $push: { tags: 'new_tag' } }
{ $pull: { tags: 'old_tag' } }Transactions
MongoDB-style transactions with sessions:
// Start a session
const session = await client.startSession({
timeoutSeconds: 3600,
defaultIsolationLevel: 'READ_COMMITTED',
});
try {
// Start transaction
const transaction = session.startTransaction('SERIALIZABLE');
// Perform operations
await users.insertOne({ name: 'Charlie' });
await profiles.insertOne({ user: 'Charlie', bio: 'Developer' });
// Commit transaction
await session.commitTransaction();
} catch (error) {
// Abort on error
await session.abortTransaction();
throw error;
} finally {
// Close session
await session.close();
}Bulk Operations
const operations = [
{
action: 'insert' as const,
document: { name: 'User1' },
},
{
action: 'update' as const,
query: { name: 'User2' },
update: { $set: { active: true } },
},
{
action: 'delete' as const,
query: { name: 'User3' },
},
];
// Execute bulk write (ordered)
const result = await col.bulkWrite(operations, { ordered: true });
// Execute bulk write (atomic - all or nothing)
const atomicResult = await col.bulkWrite(operations, { atomic: true });Index Management
// Create index
const indexName = await col.createIndex('email', {
unique: true,
sparse: false,
});
// Create compound index
const compoundIndex = await col.createCompoundIndex([
['name', 1],
['age', -1],
]);
// Create TTL index
await col.createIndex('created_at', {
indexType: 'ttl',
ttl_seconds: 3600,
});
// List indexes
const indexes = await col.listIndexes();
// Drop index
await col.dropIndex('email_1');Advanced Queries
// Find with options
const results = await col.find(
{ age: { $gte: 25 } },
{
projection: { name: 1, email: 1 },
sort: [['age', -1]],
skip: 10,
limit: 20,
hint: 'age_1',
}
);
// Upsert
await col.updateOne(
{ email: '[email protected]' },
{ $set: { name: 'New User', active: true } },
{ upsert: true }
);Configuration
import { ClientConfig } from '@tubox/client';
const config = new ClientConfig({
host: 'tubox.example.com',
port: 7188,
maxPoolSize: 20,
maxConnections: 100,
connectTimeout: 10000,
requestTimeout: 30000,
retryMaxAttempts: 3,
logLevel: 'info',
});
const client = new TuboxClient(config);Environment Variables
TUBOX_HOST- Server hostname (default: localhost)TUBOX_PORT- Server port (default: 7188)TUBOX_LOG_LEVEL- Log level (debug, info, warn, error)
Metrics & Monitoring
// Get client metrics
const metrics = client.getClientMetrics();
console.log(metrics);
// {
// total_connections: 5,
// active_connections: 2,
// pooled_connections: 3,
// total_requests: 1000,
// total_errors: 5,
// avg_latency_ms: 12.5
// }
// Get storage info
const storage = await client.getStorageInfo();
console.log(storage);
// {
// storage_used_bytes: 1048576,
// storage_quota_bytes: 500000000,
// storage_used_mb: 1,
// storage_quota_mb: 500,
// usage_percentage: 0.2
// }Error Handling
import {
TuboxException,
AuthenticationError,
UnauthorizedError,
QuotaExceededError,
DocumentNotFoundError,
} from '@tubox/client';
try {
await client.authenticate('user', 'wrong_password');
} catch (error) {
if (error instanceof AuthenticationError) {
console.error('Authentication failed:', error.message);
} else if (error instanceof UnauthorizedError) {
console.error('Not authorized:', error.message);
} else {
console.error('Unexpected error:', error);
}
}TypeScript Support
Full TypeScript definitions included:
import { Document, Query, UpdateOperators, FindOptions } from '@tubox/client';
interface User extends Document {
name: string;
email: string;
age: number;
active?: boolean;
}
const users = db.collection('users');
const user = await users.findOne<User>({ email: '[email protected]' });License
MIT
Support
For issues and questions, visit: https://github.com/tubox/tubox-client-js/issues
