@onurege3467/zerohelper
v8.0.0
Published
ZeroHelper is a versatile JavaScript library offering helper functions, validation, logging, database utilities and migration system for developers. It supports MongoDB, MySQL, SQLite, Redis, and PostgreSQL with increment/decrement operations.
Downloads
137
Maintainers
Readme
ZeroHelper 🚀
The Ultimate JavaScript Toolkit for Modern Developers
A comprehensive, production-ready library combining powerful utilities, intelligent database management, advanced caching, and seamless migration tools.
🚀 Quick Start • 📖 Documentation • 💡 Examples • 🔧 API Reference
✨ Why Choose ZeroHelper?
🎯 All-in-One Solution - From utility functions to database management, everything you need in one package
🚀 Production-Ready - Battle-tested with intelligent caching and error handling
🔥 Performance Optimized - Smart cache management with 90% fewer cache misses
🛡️ Enterprise Security - Built-in validation, sanitization, and encryption
📦 Zero Dependencies* - Lightweight with minimal external dependencies
🌐 Multi-Database Support - MySQL, PostgreSQL, SQLite, MongoDB, Redis, JSON
🚀 Quick Start
Installation
npm install @onurege3467/zerohelperBasic Usage
const helpers = require('@onurege3467/zerohelper/functions');
const createDatabase = require('@onurege3467/zerohelper/database');
// Instant utility functions
const uniqueId = helpers.random.makeUniqueId();
const isValidEmail = helpers.validation.isEmail('[email protected]');
// Powerful database with smart caching
const db = createDatabase({
adapter: 'sqlite',
config: {
filePath: './app.db',
cache: { type: 'memory', max: 1000, ttl: 300000 }
}
});
// Lightning-fast operations
await db.insert('users', { name: 'John', email: '[email protected]' });
await db.increment('users', { score: 10 }, { id: 1 }); // Smart cache update!📑 Table of Contents
🛠️ Core Features
- 🎲 Random & Generation
- ✅ Validation & Sanitization
- 🔧 Data Manipulation
- 🔒 Security & Encryption
- 📝 Advanced Logging
- 🌐 HTTP Utilities
💾 Database Engine
- 🏭 Database Factory
- 🧠 Smart Cache System
- ➕ Increment/Decrement Operations
- 🗄️ Migration Management
- 📊 Supported Adapters
📖 Advanced Topics
🛠️ Core Features
🎲 Random & Generation
Generate unique IDs, random data, and secure tokens with ease.
const { random } = helpers;
// Unique identifiers
const id = random.makeUniqueId(); // "lzx8k9x8k9"
const uuid = random.generateRandomString(16); // "AbCdEfGh12345678"
// Random data generation
const number = random.randomNumber(1, 100); // 42
const float = random.randomFloat(1.5, 5.5); // 3.14159
const emoji = random.randomEmoji(); // "😄"
const color = random.randomHex(); // "#A1B2C3"
// Array operations
const item = random.randomArray([1, 2, 3, 4, 5]); // 3✅ Validation & Sanitization
Industry-standard validation with built-in security features.
const { validation } = helpers;
// Email & contact validation
validation.isEmail('[email protected]'); // true
validation.isPhone('+1234567890'); // true
validation.isURL('https://example.com'); // true
// Security & sanitization
const clean = validation.sanitizeHTML('<script>alert("xss")</script><p>Safe</p>');
// Result: "<p>Safe</p>"
const input = validation.sanitizeInput(' <script>hack</script>Hello ', {
trim: true,
removeHTML: true,
escape: true
});
// Result: "Hello"
// Credit card validation (Luhn algorithm)
validation.validateCreditCard('4111111111111111'); // true
// Advanced schema validation
const schema = {
name: { required: true, type: 'string', minLength: 2, maxLength: 50 },
age: { required: true, type: 'number', min: 0, max: 120 },
email: { required: true, pattern: /^[^\s@]+@[^\s@]+\.[^\s@]+$/ }
};
const result = validation.validateSchema(
{ name: 'John Doe', age: 30, email: '[email protected]' },
schema
);
// Result: { isValid: true, errors: [] }🔧 Data Manipulation
Powerful array, object, and string manipulation tools.
const { array, object, string } = helpers;
// Array operations
const shuffled = array.shuffleArray([1, 2, 3, 4, 5]);
const flattened = array.flattenArray([1, [2, [3, 4]], 5]); // [1, 2, 3, 4, 5]
const grouped = array.groupBy(users, 'department');
const names = array.pluck(users, 'name');
const sorted = array.sortBy(products, 'price');
// Object manipulation
const filtered = object.filterObjectByKey(user, ['name', 'email']);
const merged = object.deepMerge(config1, config2);
// String utilities
const title = string.titleCase('hello world'); // "Hello World"
const slug = string.generateSlug('My Blog Post!'); // "my-blog-post"
const wordCount = string.wordCount('Hello world'); // 2🔒 Security & Encryption
Enterprise-grade security with encryption, hashing, and JWT support.
const { crypto } = helpers;
// Password security
const hashedPassword = crypto.hashPassword('mySecretPassword');
const isValid = crypto.verifyPassword('mySecretPassword', hashedPassword);
// Data encryption
const secret = 'myEncryptionKey';
const encrypted = crypto.encryptText('Sensitive data', secret);
const decrypted = crypto.decryptText(encrypted.encryptedText, secret, encrypted.iv);
// JWT tokens
const token = crypto.generateJWT({ userId: 123, role: 'admin' }, 'secretKey');
const payload = crypto.verifyJWT(token, 'secretKey');
// Security validation
crypto.isPasswordStrong('MyStr0ng!Pass'); // true
crypto.validateUUID('123e4567-e89b-12d3-a456-426614174000'); // true📝 Advanced Logging
Professional logging system with levels, colors, and file output.
const { logger } = helpers;
// Simple logging
logger.info('Application started', { port: 3000, env: 'production' });
logger.error('Database connection failed', { error: 'ECONNREFUSED' });
logger.warn('High memory usage detected', { memory: '85%' });
logger.debug('User session created', { userId: 123, sessionId: 'abc123' });
// Custom logger with advanced features
const customLogger = logger.createLogger({
level: 'debug', // Minimum log level
enableColors: true, // Colorized output
enableTimestamp: true, // ISO timestamps
logFile: './app.log' // File output
});
customLogger.info('Custom logger initialized');
customLogger.setLevel('warn'); // Dynamic level changes🌐 HTTP Utilities
Built-in HTTP client for API interactions.
const { http } = helpers;
// GET requests
const data = await http.fetchData('https://api.example.com/users');
// POST requests
const response = await http.postData('https://api.example.com/users', {
name: 'John Doe',
email: '[email protected]'
});💾 Database Engine
🏭 Database Factory
Universal database interface supporting multiple adapters with intelligent caching.
const createDatabase = require('@onurege3467/zerohelper/database');
// SQLite with smart caching
const sqliteDb = createDatabase({
adapter: 'sqlite',
config: {
filePath: './production.db',
cache: {
type: 'memory',
max: 1000,
ttl: 300000, // 5 minutes
updateAgeOnGet: true
}
}
});
// PostgreSQL with Redis cache
const postgresDb = createDatabase({
adapter: 'postgres',
config: {
host: 'localhost',
user: 'postgres',
password: 'password',
database: 'myapp',
cache: {
type: 'redis',
host: 'redis-server',
port: 6379,
ttl: 600,
keyPrefix: 'myapp_cache:'
}
}
});
// MongoDB with caching
const mongoDb = createDatabase({
adapter: 'mongodb',
config: {
url: 'mongodb://localhost:27017',
database: 'myapp',
cache: { type: 'memory', max: 500 }
}
});🧠 Smart Cache System
Revolutionary caching that updates intelligently instead of invalidating everything.
Traditional Cache Problems:
// ❌ Old way: Every operation clears entire cache
await db.increment('posts', { views: 1 }, { id: 1 });
const post = await db.selectOne('posts', { id: 1 }); // Cache miss - DB queryZeroHelper's Smart Cache:
// ✅ Smart way: Cache values updated directly
const post = await db.selectOne('posts', { id: 1 }); // Cached: { id: 1, views: 100 }
await db.increment('posts', { views: 1 }, { id: 1 }); // Cache updated to { id: 1, views: 101 }
const updated = await db.selectOne('posts', { id: 1 }); // From cache: { id: 1, views: 101 } ⚡Performance Benefits:
- 🚀 90% fewer cache misses
- ⚡ Zero DB queries for increment/decrement
- 💾 Selective cache updates instead of full invalidation
- 🎯 Automatic cache consistency
➕ Increment/Decrement Operations
Atomic numeric operations with smart cache integration across all database types.
// E-commerce example
await db.increment('products', { views: 1, popularity: 0.1 }, { id: productId });
await db.decrement('products', { stock: quantity }, { id: productId });
// Analytics example
await db.increment('analytics', {
page_views: 1,
unique_visitors: isUnique ? 1 : 0,
bounce_rate: bounced ? 1 : 0
}, { page: '/home', date: today });
// Gaming example
await db.increment('players', {
score: points,
level: levelUp ? 1 : 0,
coins: reward
}, { user_id: playerId });Cross-Database Support:
- SQLite/MySQL/PostgreSQL: Native SQL
field = field + value - MongoDB: Native
$incoperator - Redis: Native
HINCRBYcommand - JSON: JavaScript arithmetic operations
🗄️ Migration Management
Professional database schema versioning and migration system.
const { MigrationManager } = require('@onurege3467/zerohelper/database');
const migrationManager = new MigrationManager(db, {
migrationsDir: './migrations',
migrationsTable: 'schema_migrations'
});
// Create new migration
migrationManager.createMigration('add_user_profiles', 'Add user profile fields');
// Run migrations
await migrationManager.migrate(); // Run all pending
await migrationManager.rollback(2); // Rollback last 2
await migrationManager.status(); // Show migration status
await migrationManager.reset(); // Reset all migrationsMigration File Structure:
// migrations/1640995200000_add_user_profiles.js
module.exports = {
async up(db) {
await db.query(\`
ALTER TABLE users
ADD COLUMN avatar_url VARCHAR(255),
ADD COLUMN bio TEXT,
ADD COLUMN created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
\`);
console.log('✅ User profiles added');
},
async down(db) {
await db.query(\`
ALTER TABLE users
DROP COLUMN avatar_url,
DROP COLUMN bio,
DROP COLUMN created_at
\`);
console.log('✅ User profiles removed');
}
};📊 Supported Adapters
| Database | Status | Cache Support | Increment/Decrement | Migrations | |----------|--------|---------------|---------------------|------------| | SQLite | ✅ Full | ✅ Memory/Redis | ✅ Native SQL | ✅ Yes | | MySQL | ✅ Full | ✅ Memory/Redis | ✅ Native SQL | ✅ Yes | | PostgreSQL | ✅ Full | ✅ Memory/Redis | ✅ Native SQL | ✅ Yes | | MongoDB | ✅ Full | ✅ Memory/Redis | ✅ $inc operator | ✅ Yes | | Redis | ✅ Full | ✅ Memory/Redis | ✅ HINCRBY | ✅ Yes | | JSON File | ✅ Full | ✅ Memory/Redis | ✅ JavaScript | ✅ Yes |
💡 Examples
Real-World E-commerce Example
const createDatabase = require('@onurege3467/zerohelper/database');
const helpers = require('@onurege3467/zerohelper/functions');
class EcommerceService {
constructor() {
this.db = createDatabase({
adapter: 'mysql',
config: {
host: 'localhost',
user: 'ecommerce_user',
password: process.env.DB_PASSWORD,
database: 'ecommerce',
cache: { type: 'redis', host: 'redis', ttl: 600 }
}
});
this.logger = helpers.logger.createLogger({
level: 'info',
logFile: './ecommerce.log'
});
}
async createUser(userData) {
// Validate input
const schema = {
email: { required: true, pattern: /^[^\s@]+@[^\s@]+\.[^\s@]+$/ },
password: { required: true, minLength: 8 },
name: { required: true, minLength: 2 }
};
const validation = helpers.validation.validateSchema(userData, schema);
if (!validation.isValid) {
throw new Error(\`Validation failed: \${validation.errors.join(', ')}\`);
}
// Security
if (!helpers.crypto.isPasswordStrong(userData.password)) {
throw new Error('Password must be stronger');
}
// Create user
const hashedPassword = helpers.crypto.hashPassword(userData.password);
const userId = await this.db.insert('users', {
id: helpers.random.makeUniqueId(),
email: userData.email,
name: helpers.validation.sanitizeInput(userData.name),
password: hashedPassword,
created_at: new Date()
});
this.logger.info('User created successfully', { userId, email: userData.email });
return userId;
}
async addToCart(userId, productId, quantity) {
// Check stock availability
const product = await this.db.selectOne('products', { id: productId });
if (!product || product.stock < quantity) {
throw new Error('Insufficient stock');
}
// Add to cart and update stock atomically
await this.db.set('cart_items',
{ user_id: userId, product_id: productId, quantity },
{ user_id: userId, product_id: productId }
);
await this.db.decrement('products', { stock: quantity }, { id: productId });
await this.db.increment('products', { times_ordered: 1 }, { id: productId });
this.logger.info('Product added to cart', { userId, productId, quantity });
}
async getPopularProducts(limit = 10) {
// This will be cached automatically
return await this.db.select('products', {}, {
orderBy: 'times_ordered DESC',
limit
});
}
}Analytics Dashboard Example
class AnalyticsService {
constructor() {
this.db = createDatabase({
adapter: 'postgres',
config: {
host: process.env.PG_HOST,
database: 'analytics',
cache: { type: 'memory', max: 2000, ttl: 180000 } // 3 minutes
}
});
}
async trackPageView(data) {
const today = new Date().toISOString().split('T')[0];
// Validate and sanitize
const cleanData = {
page: helpers.validation.sanitizeInput(data.page),
user_agent: helpers.validation.sanitizeInput(data.userAgent),
ip: data.ip,
referrer: helpers.validation.sanitizeInput(data.referrer)
};
// Track multiple metrics atomically
await this.db.increment('daily_stats', {
page_views: 1,
unique_visitors: data.isUnique ? 1 : 0,
bounce_rate: data.bounced ? 1 : 0
}, { date: today, page: cleanData.page });
// Track real-time metrics
await this.db.increment('realtime_stats', {
current_visitors: 1
}, { page: cleanData.page });
helpers.logger.info('Page view tracked', cleanData);
}
async getDashboardData(dateRange) {
const [dailyStats, topPages, realtime] = await Promise.all([
this.db.select('daily_stats', {
date: { $gte: dateRange.start, $lte: dateRange.end }
}),
this.db.select('daily_stats', {}, {
orderBy: 'page_views DESC',
limit: 10
}),
this.db.select('realtime_stats')
]);
return { dailyStats, topPages, realtime };
}
}🔧 API Reference
Database Operations
Basic CRUD
// Create
const id = await db.insert('table', data);
const count = await db.bulkInsert('table', dataArray);
// Read
const rows = await db.select('table', whereConditions);
const row = await db.selectOne('table', whereConditions);
// Update
const affected = await db.update('table', newData, whereConditions);
const result = await db.set('table', data, whereConditions); // Upsert
// Delete
const deleted = await db.delete('table', whereConditions);Advanced Operations
// Atomic increment/decrement
await db.increment('table', { field1: amount1, field2: amount2 }, where);
await db.decrement('table', { field1: amount1, field2: amount2 }, where);
// Cache management
db.clearAllCache();
const stats = db.getCacheStats();
// Connection management
await db.close();Utility Functions
Random & Generation
helpers.random.makeUniqueId() // Unique ID
helpers.random.randomArray(array) // Random array element
helpers.random.randomText(length) // Random string
helpers.random.randomNumber(min, max) // Random integer
helpers.random.randomFloat(min, max) // Random float
helpers.random.randomEmoji() // Random emoji
helpers.random.randomHex() // Random hex colorValidation & Security
helpers.validation.isEmail(email) // Email validation
helpers.validation.isPhone(phone) // Phone validation
helpers.validation.isURL(url) // URL validation
helpers.validation.sanitizeHTML(html) // HTML sanitization
helpers.validation.validateCreditCard(number) // Credit card validation
helpers.validation.validateSchema(data, schema) // Schema validation
helpers.validation.sanitizeInput(input, options) // Input sanitization
helpers.crypto.hashPassword(password) // Hash password
helpers.crypto.verifyPassword(password, hash) // Verify password
helpers.crypto.encryptText(text, secret) // Encrypt data
helpers.crypto.decryptText(encrypted, secret, iv) // Decrypt data
helpers.crypto.generateJWT(payload, secret) // Generate JWT
helpers.crypto.verifyJWT(token, secret) // Verify JWTData Manipulation
helpers.array.shuffleArray(array) // Shuffle array
helpers.array.flattenArray(array) // Flatten nested array
helpers.array.groupBy(array, key) // Group array by key
helpers.array.pluck(array, key) // Extract property values
helpers.array.sortBy(array, key) // Sort array by property
helpers.object.filterObjectByKey(obj, keys) // Filter object properties
helpers.object.deepMerge(obj1, obj2) // Deep merge objects
helpers.string.titleCase(string) // Convert to title case
helpers.string.generateSlug(string) // Generate URL slug
helpers.string.wordCount(string) // Count wordsMath & Statistics
helpers.math.mean(array) // Calculate average
helpers.math.median(array) // Calculate median
helpers.math.variance(array) // Calculate variance
helpers.math.standardDeviation(array) // Calculate std deviation
helpers.math.sum(array) // Sum array values
helpers.math.max(array) // Find maximum
helpers.math.min(array) // Find minimum
helpers.math.range(start, end) // Generate number range
helpers.math.isPrime(number) // Check if prime⚡ Performance Tips
Database Optimization
- Use Caching: Enable memory or Redis cache for frequently accessed data
- Batch Operations: Use `bulkInsert` for multiple records
- Smart Queries: Leverage where conditions to minimize data transfer
- Index Strategy: Create proper database indexes for your queries
Cache Strategy
// High-traffic read operations
const db = createDatabase({
adapter: 'mysql',
config: {
// ... connection config
cache: {
type: 'redis',
max: 10000,
ttl: 3600, // 1 hour for static data
updateAgeOnGet: true
}
}
});
// Frequent increment operations benefit from smart cache
await db.increment('counters', { views: 1 }, { page_id: 123 }); // No cache miss!🔧 Configuration
Environment Variables
# Database
DB_HOST=localhost
DB_USER=myuser
DB_PASSWORD=mypassword
DB_NAME=mydatabase
# Redis Cache
REDIS_HOST=localhost
REDIS_PORT=6379
REDIS_PASSWORD=redispassword
# Security
JWT_SECRET=your-super-secret-key
ENCRYPTION_KEY=your-encryption-key
# Logging
LOG_LEVEL=info
LOG_FILE=./app.log🐛 Troubleshooting
Common Issues
Cache Connection Issues
// Handle Redis connection failures gracefully
const db = createDatabase({
adapter: 'mysql',
config: {
// ... mysql config
cache: {
type: 'redis',
host: 'redis-server',
// Fallback to memory cache on Redis failure
fallbackToMemory: true
}
}
});Debug Mode
// Enable detailed logging
const logger = helpers.logger.createLogger({
level: 'debug',
enableColors: true,
logFile: './debug.log'
});
// Monitor cache performance
setInterval(() => {
console.log('Cache Stats:', db.getCacheStats());
}, 30000);🙏 Acknowledgments
- Built with ❤️ by Onure9e
- Inspired by the need for a comprehensive, production-ready JavaScript toolkit
- Special thanks to the open-source community
⭐ Star this repository if ZeroHelper helped you build something amazing!
Made with 💻 and ☕ by developers, for developers.
