WorkerSQL Node.js SDK
WorkerSQL Node.js SDK
Section titled “WorkerSQL Node.js SDK”A Node.js SDK for WorkerSQL - bringing MySQL-compatible database operations to the edge with Cloudflare Workers.
Features
Section titled “Features”- 🚀 Edge-Native: Run SQL queries at the edge for ultra-low latency
- 🔒 Secure: Built-in SQL injection prevention and schema validation
- 📊 MySQL Compatible: Familiar SQL syntax with MySQL compatibility
- 🔄 Connection Pooling: Efficient connection management with automatic pooling
- 🔁 Automatic Retries: Exponential backoff retry logic for transient failures
- 📡 WebSocket Transactions: Sticky sessions for ACID transactions
- 📝 Type Safe: Full TypeScript support with type definitions
- 🧪 Well Tested: Comprehensive test coverage
- 📚 Well Documented: Complete API documentation and examples
Installation
Section titled “Installation”npm install @workersql/node-sdk
Quick Start
Section titled “Quick Start”Using DSN String
Section titled “Using DSN String”import { WorkerSQLClient } from '@workersql/node-sdk';
// Connect using DSNconst client = new WorkerSQLClient('workersql://username:[email protected]:443/mydb?apiKey=your-key');
// Execute a queryconst result = await client.query('SELECT * FROM users WHERE id = ?', [1]);console.log(result.data);
// Close the connectionawait client.close();
Using Configuration Object
Section titled “Using Configuration Object”import { WorkerSQLClient } from '@workersql/node-sdk';
const client = new WorkerSQLClient({ host: 'api.workersql.com', port: 443, database: 'mydb', username: 'myuser', password: 'mypass', apiKey: 'your-api-key', ssl: true, pooling: { enabled: true, minConnections: 2, maxConnections: 10 }});
// Execute queriesconst users = await client.query('SELECT * FROM users');console.log(users.data);
await client.close();
DSN Format
Section titled “DSN Format”The DSN (Data Source Name) follows this format:
workersql://[username[:password]@]host[:port][/database][?param1=value1¶m2=value2]
DSN Parameters
Section titled “DSN Parameters”apiKey
: API authentication keyssl
: Enable/disable SSL (default: true)timeout
: Request timeout in milliseconds (default: 30000)retryAttempts
: Number of retry attempts (default: 3)pooling
: Enable/disable connection pooling (default: true)minConnections
: Minimum pool connections (default: 1)maxConnections
: Maximum pool connections (default: 10)
DSN Examples
Section titled “DSN Examples”workersql://user:[email protected]/mydb?apiKey=abc123workersql://api.workersql.com/mydb?apiKey=abc123&pooling=true&maxConnections=20workersql://user:pass@localhost:8787/test?ssl=false&timeout=5000
Configuration Options
Section titled “Configuration Options”interface WorkerSQLClientConfig { // Connection details host: string; port?: number; username?: string; password?: string; database?: string;
// API configuration apiEndpoint?: string; // Auto-constructed from host/port if not provided apiKey?: string;
// Connection options ssl?: boolean; // Default: true timeout?: number; // Default: 30000ms
// Retry configuration retryAttempts?: number; // Default: 3 retryDelay?: number; // Default: 1000ms
// Connection pooling pooling?: { enabled?: boolean; // Default: true minConnections?: number; // Default: 1 maxConnections?: number; // Default: 10 idleTimeout?: number; // Default: 300000ms (5 min) };
// Or use DSN string dsn?: string;}
API Reference
Section titled “API Reference”WorkerSQLClient
Section titled “WorkerSQLClient”query(sql, params?, options?)
Section titled “query(sql, params?, options?)”Execute a single SQL query.
const result = await client.query( 'SELECT * FROM users WHERE age > ?', [18], { timeout: 5000 });
console.log(result.data); // Query resultsconsole.log(result.rowCount); // Number of rowsconsole.log(result.cached); // Whether result was cached
batchQuery(queries, options?)
Section titled “batchQuery(queries, options?)”Execute multiple queries in batch.
const results = await client.batchQuery([], { transaction: true, stopOnError: true});
transaction(callback)
Section titled “transaction(callback)”Execute queries within a transaction using WebSocket sticky sessions.
await client.transaction(async (txn) => { await txn.query('INSERT INTO accounts (name, balance) VALUES (?, ?)', ['Alice', 1000]); await txn.query('INSERT INTO accounts (name, balance) VALUES (?, ?)', ['Bob', 500]); // Auto-commits on success, rolls back on error});
healthCheck()
Section titled “healthCheck()”Check service health.
const health = await client.healthCheck();console.log(health.status); // 'healthy' | 'degraded' | 'unhealthy'
getPoolStats()
Section titled “getPoolStats()”Get connection pool statistics.
const stats = client.getPoolStats();console.log(stats.total); // Total connectionsconsole.log(stats.active); // Active connectionsconsole.log(stats.idle); // Idle connections
close()
Section titled “close()”Close the client and release all connections.
await client.close();
Error Handling
Section titled “Error Handling”The SDK provides detailed error information through the ValidationError
class:
import { WorkerSQLClient, ValidationError } from '@workersql/node-sdk';
try { const result = await client.query('SELECT * FROM users');} catch (error) { if (error instanceof ValidationError) { console.error('Error code:', error.code); console.error('Error message:', error.message); console.error('Error details:', error.details); }}
Error Codes
Section titled “Error Codes”INVALID_QUERY
: SQL syntax or validation errorCONNECTION_ERROR
: Network or connection failureTIMEOUT_ERROR
: Operation timed outAUTH_ERROR
: Authentication failedPERMISSION_ERROR
: Insufficient permissionsRESOURCE_LIMIT
: Resource limit exceededINTERNAL_ERROR
: Internal server error
Connection Pooling
Section titled “Connection Pooling”The SDK includes automatic connection pooling for optimal performance:
const client = new WorkerSQLClient({ host: 'api.workersql.com', database: 'mydb', apiKey: 'your-key', pooling: { enabled: true, minConnections: 2, // Always maintain 2 connections maxConnections: 20, // Scale up to 20 connections idleTimeout: 300000 // Close idle connections after 5 minutes }});
// Connections are automatically acquired and releasedconst result1 = await client.query('SELECT * FROM users');const result2 = await client.query('SELECT * FROM orders');
// Check pool statusconsole.log(client.getPoolStats());
Automatic Retries
Section titled “Automatic Retries”The SDK automatically retries failed requests with exponential backoff:
const client = new WorkerSQLClient({ host: 'api.workersql.com', database: 'mydb', apiKey: 'your-key', retryAttempts: 5, // Retry up to 5 times retryDelay: 1000 // Start with 1 second delay});
// Automatically retries on transient errors:// - CONNECTION_ERROR// - TIMEOUT_ERROR// - RESOURCE_LIMIT// - Network errors (ECONNREFUSED, ETIMEDOUT, etc.)
WebSocket Transactions
Section titled “WebSocket Transactions”For ACID transactions, the SDK uses WebSocket connections to maintain sticky sessions:
// WebSocket transactions are enabled by defaultawait client.transaction(async (txn) => { // All queries in this callback use the same WebSocket connection // ensuring they execute on the same shard
const balance = await txn.query('SELECT balance FROM accounts WHERE id = ?', [1]);
if (balance.data[0].balance >= 100) { await txn.query('UPDATE accounts SET balance = balance - 100 WHERE id = ?', [1]); await txn.query('UPDATE accounts SET balance = balance + 100 WHERE id = ?', [2]); }
// Automatically commits on success // Automatically rolls back on error});
Prepared Statements
Section titled “Prepared Statements”The SDK uses parameterized queries to prevent SQL injection:
// ✅ Safe - uses prepared statementsawait client.query( 'SELECT * FROM users WHERE email = ? AND status = ?',);
// ❌ Unsafe - don't concatenate user input// await client.query(`SELECT * FROM users WHERE email = '${userEmail}'`);
TypeScript Support
Section titled “TypeScript Support”The SDK is written in TypeScript and includes full type definitions:
import { WorkerSQLClient, QueryResponse, BatchQueryResponse, HealthCheckResponse, ValidationError} from '@workersql/node-sdk';
const client: WorkerSQLClient = new WorkerSQLClient({ host: 'api.workersql.com', database: 'mydb', apiKey: 'your-key'});
const result: QueryResponse = await client.query('SELECT * FROM users');const health: HealthCheckResponse = await client.healthCheck();
Examples
Section titled “Examples”Basic CRUD Operations
Section titled “Basic CRUD Operations”// Createconst insert = await client.query( 'INSERT INTO users (name, email) VALUES (?, ?)',);console.log('Inserted ID:', insert.data);
// Readconst users = await client.query('SELECT * FROM users WHERE id = ?', [1]);console.log('User:', users.data[0]);
// Update
// Deleteawait client.query('DELETE FROM users WHERE id = ?', [1]);
Batch Operations
Section titled “Batch Operations”const queries = [ { sql: 'INSERT INTO logs (message) VALUES (?)', params: ['Log 1'] }, { sql: 'INSERT INTO logs (message) VALUES (?)', params: ['Log 2'] }, { sql: 'INSERT INTO logs (message) VALUES (?)', params: ['Log 3'] }];
const results = await client.batchQuery(queries, { transaction: false, stopOnError: false});
console.log(`${results.results.filter(r => r.success).length} queries succeeded`);
Transaction with Error Handling
Section titled “Transaction with Error Handling”try { await client.transaction(async (txn) => { await txn.query('UPDATE accounts SET balance = balance - 100 WHERE id = ?', [1]);
// Simulate an error const balance = await txn.query('SELECT balance FROM accounts WHERE id = ?', [1]); if (balance.data[0].balance < 0) { throw new Error('Insufficient funds'); }
await txn.query('UPDATE accounts SET balance = balance + 100 WHERE id = ?', [2]); });
console.log('Transaction committed');} catch (error) { console.error('Transaction rolled back:', error);}
Development
Section titled “Development”# Install dependenciesnpm install
# Build the SDKnpm run build
# Run testsnpm test
# Run linternpm run lint
# Format codenpm run format
Contributing
Section titled “Contributing”Contributions are welcome! Please see CONTRIBUTING.md for details.
License
Section titled “License”Apache-2.0 - see LICENSE for details.
Support
Section titled “Support”- Documentation: https://docs.workersql.com
- GitHub Issues: https://github.com/healthfees-org/workersql/issues
- Community Forum: https://community.workersql.com
Changelog
Section titled “Changelog”See CHANGELOG.md for version history and release notes.