@onurege3467/zerohelper 7.1.0 → 8.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +762 -0
- package/database/IDatabase.js +18 -0
- package/database/cacheWrapper.js +526 -62
- package/database/index.js +9 -2
- package/database/json.js +59 -0
- package/database/migration.js +227 -0
- package/database/mongodb.js +45 -0
- package/database/mysql.js +61 -0
- package/database/pg.js +64 -0
- package/database/redis.js +342 -0
- package/database/sqlite.js +69 -0
- package/functions/index.js +267 -0
- package/package.json +11 -7
- package/.snapshots/config.json +0 -151
- package/.snapshots/readme.md +0 -11
- package/.snapshots/sponsors.md +0 -44
- package/1.json +0 -15
- package/readme.md +0 -418
- package/test.js +0 -261
- package/test_mysqlonly.js +0 -144
package/README.md
ADDED
|
@@ -0,0 +1,762 @@
|
|
|
1
|
+
# ZeroHelper 🚀
|
|
2
|
+
|
|
3
|
+
<div align="center">
|
|
4
|
+
|
|
5
|
+
**The Ultimate JavaScript Toolkit for Modern Developers**
|
|
6
|
+
|
|
7
|
+
*A comprehensive, production-ready library combining powerful utilities, intelligent database management, advanced caching, and seamless migration tools.*
|
|
8
|
+
|
|
9
|
+
[🚀 Quick Start](#-quick-start) • [📖 Documentation](#-documentation) • [💡 Examples](#-examples) • [🔧 API Reference](#-api-reference)
|
|
10
|
+
|
|
11
|
+
</div>
|
|
12
|
+
|
|
13
|
+
---
|
|
14
|
+
|
|
15
|
+
## ✨ Why Choose ZeroHelper?
|
|
16
|
+
|
|
17
|
+
🎯 **All-in-One Solution** - From utility functions to database management, everything you need in one package
|
|
18
|
+
🚀 **Production-Ready** - Battle-tested with intelligent caching and error handling
|
|
19
|
+
🔥 **Performance Optimized** - Smart cache management with 90% fewer cache misses
|
|
20
|
+
🛡️ **Enterprise Security** - Built-in validation, sanitization, and encryption
|
|
21
|
+
📦 **Zero Dependencies*** - Lightweight with minimal external dependencies
|
|
22
|
+
🌐 **Multi-Database Support** - MySQL, PostgreSQL, SQLite, MongoDB, Redis, JSON
|
|
23
|
+
|
|
24
|
+
---
|
|
25
|
+
|
|
26
|
+
## 🚀 Quick Start
|
|
27
|
+
|
|
28
|
+
### Installation
|
|
29
|
+
|
|
30
|
+
```bash
|
|
31
|
+
npm install @onurege3467/zerohelper
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
### Basic Usage
|
|
35
|
+
|
|
36
|
+
```javascript
|
|
37
|
+
const helpers = require('@onurege3467/zerohelper/functions');
|
|
38
|
+
const createDatabase = require('@onurege3467/zerohelper/database');
|
|
39
|
+
|
|
40
|
+
// Instant utility functions
|
|
41
|
+
const uniqueId = helpers.random.makeUniqueId();
|
|
42
|
+
const isValidEmail = helpers.validation.isEmail('user@example.com');
|
|
43
|
+
|
|
44
|
+
// Powerful database with smart caching
|
|
45
|
+
const db = createDatabase({
|
|
46
|
+
adapter: 'sqlite',
|
|
47
|
+
config: {
|
|
48
|
+
filePath: './app.db',
|
|
49
|
+
cache: { type: 'memory', max: 1000, ttl: 300000 }
|
|
50
|
+
}
|
|
51
|
+
});
|
|
52
|
+
|
|
53
|
+
// Lightning-fast operations
|
|
54
|
+
await db.insert('users', { name: 'John', email: 'john@example.com' });
|
|
55
|
+
await db.increment('users', { score: 10 }, { id: 1 }); // Smart cache update!
|
|
56
|
+
```
|
|
57
|
+
|
|
58
|
+
---
|
|
59
|
+
|
|
60
|
+
## 📑 Table of Contents
|
|
61
|
+
|
|
62
|
+
### 🛠️ Core Features
|
|
63
|
+
- [🎲 Random & Generation](#-random--generation)
|
|
64
|
+
- [✅ Validation & Sanitization](#-validation--sanitization)
|
|
65
|
+
- [🔧 Data Manipulation](#-data-manipulation)
|
|
66
|
+
- [🔒 Security & Encryption](#-security--encryption)
|
|
67
|
+
- [📝 Advanced Logging](#-advanced-logging)
|
|
68
|
+
- [🌐 HTTP Utilities](#-http-utilities)
|
|
69
|
+
|
|
70
|
+
### 💾 Database Engine
|
|
71
|
+
- [🏭 Database Factory](#-database-factory)
|
|
72
|
+
- [🧠 Smart Cache System](#-smart-cache-system)
|
|
73
|
+
- [➕ Increment/Decrement Operations](#-incrementdecrement-operations)
|
|
74
|
+
- [🗄️ Migration Management](#-migration-management)
|
|
75
|
+
- [📊 Supported Adapters](#-supported-adapters)
|
|
76
|
+
|
|
77
|
+
### 📖 Advanced Topics
|
|
78
|
+
- [🔧 Configuration](#-configuration)
|
|
79
|
+
- [⚡ Performance Tips](#-performance-tips)
|
|
80
|
+
- [🐛 Troubleshooting](#-troubleshooting)
|
|
81
|
+
|
|
82
|
+
---
|
|
83
|
+
|
|
84
|
+
## 🛠️ Core Features
|
|
85
|
+
|
|
86
|
+
### 🎲 Random & Generation
|
|
87
|
+
|
|
88
|
+
Generate unique IDs, random data, and secure tokens with ease.
|
|
89
|
+
|
|
90
|
+
```javascript
|
|
91
|
+
const { random } = helpers;
|
|
92
|
+
|
|
93
|
+
// Unique identifiers
|
|
94
|
+
const id = random.makeUniqueId(); // "lzx8k9x8k9"
|
|
95
|
+
const uuid = random.generateRandomString(16); // "AbCdEfGh12345678"
|
|
96
|
+
|
|
97
|
+
// Random data generation
|
|
98
|
+
const number = random.randomNumber(1, 100); // 42
|
|
99
|
+
const float = random.randomFloat(1.5, 5.5); // 3.14159
|
|
100
|
+
const emoji = random.randomEmoji(); // "😄"
|
|
101
|
+
const color = random.randomHex(); // "#A1B2C3"
|
|
102
|
+
|
|
103
|
+
// Array operations
|
|
104
|
+
const item = random.randomArray([1, 2, 3, 4, 5]); // 3
|
|
105
|
+
```
|
|
106
|
+
|
|
107
|
+
### ✅ Validation & Sanitization
|
|
108
|
+
|
|
109
|
+
Industry-standard validation with built-in security features.
|
|
110
|
+
|
|
111
|
+
```javascript
|
|
112
|
+
const { validation } = helpers;
|
|
113
|
+
|
|
114
|
+
// Email & contact validation
|
|
115
|
+
validation.isEmail('user@domain.com'); // true
|
|
116
|
+
validation.isPhone('+1234567890'); // true
|
|
117
|
+
validation.isURL('https://example.com'); // true
|
|
118
|
+
|
|
119
|
+
// Security & sanitization
|
|
120
|
+
const clean = validation.sanitizeHTML('<script>alert("xss")</script><p>Safe</p>');
|
|
121
|
+
// Result: "<p>Safe</p>"
|
|
122
|
+
|
|
123
|
+
const input = validation.sanitizeInput(' <script>hack</script>Hello ', {
|
|
124
|
+
trim: true,
|
|
125
|
+
removeHTML: true,
|
|
126
|
+
escape: true
|
|
127
|
+
});
|
|
128
|
+
// Result: "Hello"
|
|
129
|
+
|
|
130
|
+
// Credit card validation (Luhn algorithm)
|
|
131
|
+
validation.validateCreditCard('4111111111111111'); // true
|
|
132
|
+
|
|
133
|
+
// Advanced schema validation
|
|
134
|
+
const schema = {
|
|
135
|
+
name: { required: true, type: 'string', minLength: 2, maxLength: 50 },
|
|
136
|
+
age: { required: true, type: 'number', min: 0, max: 120 },
|
|
137
|
+
email: { required: true, pattern: /^[^\s@]+@[^\s@]+\.[^\s@]+$/ }
|
|
138
|
+
};
|
|
139
|
+
|
|
140
|
+
const result = validation.validateSchema(
|
|
141
|
+
{ name: 'John Doe', age: 30, email: 'john@example.com' },
|
|
142
|
+
schema
|
|
143
|
+
);
|
|
144
|
+
// Result: { isValid: true, errors: [] }
|
|
145
|
+
```
|
|
146
|
+
|
|
147
|
+
### 🔧 Data Manipulation
|
|
148
|
+
|
|
149
|
+
Powerful array, object, and string manipulation tools.
|
|
150
|
+
|
|
151
|
+
```javascript
|
|
152
|
+
const { array, object, string } = helpers;
|
|
153
|
+
|
|
154
|
+
// Array operations
|
|
155
|
+
const shuffled = array.shuffleArray([1, 2, 3, 4, 5]);
|
|
156
|
+
const flattened = array.flattenArray([1, [2, [3, 4]], 5]); // [1, 2, 3, 4, 5]
|
|
157
|
+
const grouped = array.groupBy(users, 'department');
|
|
158
|
+
const names = array.pluck(users, 'name');
|
|
159
|
+
const sorted = array.sortBy(products, 'price');
|
|
160
|
+
|
|
161
|
+
// Object manipulation
|
|
162
|
+
const filtered = object.filterObjectByKey(user, ['name', 'email']);
|
|
163
|
+
const merged = object.deepMerge(config1, config2);
|
|
164
|
+
|
|
165
|
+
// String utilities
|
|
166
|
+
const title = string.titleCase('hello world'); // "Hello World"
|
|
167
|
+
const slug = string.generateSlug('My Blog Post!'); // "my-blog-post"
|
|
168
|
+
const wordCount = string.wordCount('Hello world'); // 2
|
|
169
|
+
```
|
|
170
|
+
|
|
171
|
+
### 🔒 Security & Encryption
|
|
172
|
+
|
|
173
|
+
Enterprise-grade security with encryption, hashing, and JWT support.
|
|
174
|
+
|
|
175
|
+
```javascript
|
|
176
|
+
const { crypto } = helpers;
|
|
177
|
+
|
|
178
|
+
// Password security
|
|
179
|
+
const hashedPassword = crypto.hashPassword('mySecretPassword');
|
|
180
|
+
const isValid = crypto.verifyPassword('mySecretPassword', hashedPassword);
|
|
181
|
+
|
|
182
|
+
// Data encryption
|
|
183
|
+
const secret = 'myEncryptionKey';
|
|
184
|
+
const encrypted = crypto.encryptText('Sensitive data', secret);
|
|
185
|
+
const decrypted = crypto.decryptText(encrypted.encryptedText, secret, encrypted.iv);
|
|
186
|
+
|
|
187
|
+
// JWT tokens
|
|
188
|
+
const token = crypto.generateJWT({ userId: 123, role: 'admin' }, 'secretKey');
|
|
189
|
+
const payload = crypto.verifyJWT(token, 'secretKey');
|
|
190
|
+
|
|
191
|
+
// Security validation
|
|
192
|
+
crypto.isPasswordStrong('MyStr0ng!Pass'); // true
|
|
193
|
+
crypto.validateUUID('123e4567-e89b-12d3-a456-426614174000'); // true
|
|
194
|
+
```
|
|
195
|
+
|
|
196
|
+
### 📝 Advanced Logging
|
|
197
|
+
|
|
198
|
+
Professional logging system with levels, colors, and file output.
|
|
199
|
+
|
|
200
|
+
```javascript
|
|
201
|
+
const { logger } = helpers;
|
|
202
|
+
|
|
203
|
+
// Simple logging
|
|
204
|
+
logger.info('Application started', { port: 3000, env: 'production' });
|
|
205
|
+
logger.error('Database connection failed', { error: 'ECONNREFUSED' });
|
|
206
|
+
logger.warn('High memory usage detected', { memory: '85%' });
|
|
207
|
+
logger.debug('User session created', { userId: 123, sessionId: 'abc123' });
|
|
208
|
+
|
|
209
|
+
// Custom logger with advanced features
|
|
210
|
+
const customLogger = logger.createLogger({
|
|
211
|
+
level: 'debug', // Minimum log level
|
|
212
|
+
enableColors: true, // Colorized output
|
|
213
|
+
enableTimestamp: true, // ISO timestamps
|
|
214
|
+
logFile: './app.log' // File output
|
|
215
|
+
});
|
|
216
|
+
|
|
217
|
+
customLogger.info('Custom logger initialized');
|
|
218
|
+
customLogger.setLevel('warn'); // Dynamic level changes
|
|
219
|
+
```
|
|
220
|
+
|
|
221
|
+
### 🌐 HTTP Utilities
|
|
222
|
+
|
|
223
|
+
Built-in HTTP client for API interactions.
|
|
224
|
+
|
|
225
|
+
```javascript
|
|
226
|
+
const { http } = helpers;
|
|
227
|
+
|
|
228
|
+
// GET requests
|
|
229
|
+
const data = await http.fetchData('https://api.example.com/users');
|
|
230
|
+
|
|
231
|
+
// POST requests
|
|
232
|
+
const response = await http.postData('https://api.example.com/users', {
|
|
233
|
+
name: 'John Doe',
|
|
234
|
+
email: 'john@example.com'
|
|
235
|
+
});
|
|
236
|
+
```
|
|
237
|
+
|
|
238
|
+
---
|
|
239
|
+
|
|
240
|
+
## 💾 Database Engine
|
|
241
|
+
|
|
242
|
+
### 🏭 Database Factory
|
|
243
|
+
|
|
244
|
+
Universal database interface supporting multiple adapters with intelligent caching.
|
|
245
|
+
|
|
246
|
+
```javascript
|
|
247
|
+
const createDatabase = require('@onurege3467/zerohelper/database');
|
|
248
|
+
|
|
249
|
+
// SQLite with smart caching
|
|
250
|
+
const sqliteDb = createDatabase({
|
|
251
|
+
adapter: 'sqlite',
|
|
252
|
+
config: {
|
|
253
|
+
filePath: './production.db',
|
|
254
|
+
cache: {
|
|
255
|
+
type: 'memory',
|
|
256
|
+
max: 1000,
|
|
257
|
+
ttl: 300000, // 5 minutes
|
|
258
|
+
updateAgeOnGet: true
|
|
259
|
+
}
|
|
260
|
+
}
|
|
261
|
+
});
|
|
262
|
+
|
|
263
|
+
// PostgreSQL with Redis cache
|
|
264
|
+
const postgresDb = createDatabase({
|
|
265
|
+
adapter: 'postgres',
|
|
266
|
+
config: {
|
|
267
|
+
host: 'localhost',
|
|
268
|
+
user: 'postgres',
|
|
269
|
+
password: 'password',
|
|
270
|
+
database: 'myapp',
|
|
271
|
+
cache: {
|
|
272
|
+
type: 'redis',
|
|
273
|
+
host: 'redis-server',
|
|
274
|
+
port: 6379,
|
|
275
|
+
ttl: 600,
|
|
276
|
+
keyPrefix: 'myapp_cache:'
|
|
277
|
+
}
|
|
278
|
+
}
|
|
279
|
+
});
|
|
280
|
+
|
|
281
|
+
// MongoDB with caching
|
|
282
|
+
const mongoDb = createDatabase({
|
|
283
|
+
adapter: 'mongodb',
|
|
284
|
+
config: {
|
|
285
|
+
url: 'mongodb://localhost:27017',
|
|
286
|
+
database: 'myapp',
|
|
287
|
+
cache: { type: 'memory', max: 500 }
|
|
288
|
+
}
|
|
289
|
+
});
|
|
290
|
+
```
|
|
291
|
+
|
|
292
|
+
### 🧠 Smart Cache System
|
|
293
|
+
|
|
294
|
+
Revolutionary caching that updates intelligently instead of invalidating everything.
|
|
295
|
+
|
|
296
|
+
#### Traditional Cache Problems:
|
|
297
|
+
```javascript
|
|
298
|
+
// ❌ Old way: Every operation clears entire cache
|
|
299
|
+
await db.increment('posts', { views: 1 }, { id: 1 });
|
|
300
|
+
const post = await db.selectOne('posts', { id: 1 }); // Cache miss - DB query
|
|
301
|
+
```
|
|
302
|
+
|
|
303
|
+
#### ZeroHelper's Smart Cache:
|
|
304
|
+
```javascript
|
|
305
|
+
// ✅ Smart way: Cache values updated directly
|
|
306
|
+
const post = await db.selectOne('posts', { id: 1 }); // Cached: { id: 1, views: 100 }
|
|
307
|
+
await db.increment('posts', { views: 1 }, { id: 1 }); // Cache updated to { id: 1, views: 101 }
|
|
308
|
+
const updated = await db.selectOne('posts', { id: 1 }); // From cache: { id: 1, views: 101 } ⚡
|
|
309
|
+
```
|
|
310
|
+
|
|
311
|
+
#### Performance Benefits:
|
|
312
|
+
- 🚀 **90% fewer cache misses**
|
|
313
|
+
- ⚡ **Zero DB queries for increment/decrement**
|
|
314
|
+
- 💾 **Selective cache updates instead of full invalidation**
|
|
315
|
+
- 🎯 **Automatic cache consistency**
|
|
316
|
+
|
|
317
|
+
### ➕ Increment/Decrement Operations
|
|
318
|
+
|
|
319
|
+
Atomic numeric operations with smart cache integration across all database types.
|
|
320
|
+
|
|
321
|
+
```javascript
|
|
322
|
+
// E-commerce example
|
|
323
|
+
await db.increment('products', { views: 1, popularity: 0.1 }, { id: productId });
|
|
324
|
+
await db.decrement('products', { stock: quantity }, { id: productId });
|
|
325
|
+
|
|
326
|
+
// Analytics example
|
|
327
|
+
await db.increment('analytics', {
|
|
328
|
+
page_views: 1,
|
|
329
|
+
unique_visitors: isUnique ? 1 : 0,
|
|
330
|
+
bounce_rate: bounced ? 1 : 0
|
|
331
|
+
}, { page: '/home', date: today });
|
|
332
|
+
|
|
333
|
+
// Gaming example
|
|
334
|
+
await db.increment('players', {
|
|
335
|
+
score: points,
|
|
336
|
+
level: levelUp ? 1 : 0,
|
|
337
|
+
coins: reward
|
|
338
|
+
}, { user_id: playerId });
|
|
339
|
+
```
|
|
340
|
+
|
|
341
|
+
#### Cross-Database Support:
|
|
342
|
+
- **SQLite/MySQL/PostgreSQL**: Native SQL `field = field + value`
|
|
343
|
+
- **MongoDB**: Native `$inc` operator
|
|
344
|
+
- **Redis**: Native `HINCRBY` command
|
|
345
|
+
- **JSON**: JavaScript arithmetic operations
|
|
346
|
+
|
|
347
|
+
### 🗄️ Migration Management
|
|
348
|
+
|
|
349
|
+
Professional database schema versioning and migration system.
|
|
350
|
+
|
|
351
|
+
```javascript
|
|
352
|
+
const { MigrationManager } = require('@onurege3467/zerohelper/database');
|
|
353
|
+
|
|
354
|
+
const migrationManager = new MigrationManager(db, {
|
|
355
|
+
migrationsDir: './migrations',
|
|
356
|
+
migrationsTable: 'schema_migrations'
|
|
357
|
+
});
|
|
358
|
+
|
|
359
|
+
// Create new migration
|
|
360
|
+
migrationManager.createMigration('add_user_profiles', 'Add user profile fields');
|
|
361
|
+
|
|
362
|
+
// Run migrations
|
|
363
|
+
await migrationManager.migrate(); // Run all pending
|
|
364
|
+
await migrationManager.rollback(2); // Rollback last 2
|
|
365
|
+
await migrationManager.status(); // Show migration status
|
|
366
|
+
await migrationManager.reset(); // Reset all migrations
|
|
367
|
+
```
|
|
368
|
+
|
|
369
|
+
#### Migration File Structure:
|
|
370
|
+
```javascript
|
|
371
|
+
// migrations/1640995200000_add_user_profiles.js
|
|
372
|
+
module.exports = {
|
|
373
|
+
async up(db) {
|
|
374
|
+
await db.query(\`
|
|
375
|
+
ALTER TABLE users
|
|
376
|
+
ADD COLUMN avatar_url VARCHAR(255),
|
|
377
|
+
ADD COLUMN bio TEXT,
|
|
378
|
+
ADD COLUMN created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
|
|
379
|
+
\`);
|
|
380
|
+
console.log('✅ User profiles added');
|
|
381
|
+
},
|
|
382
|
+
|
|
383
|
+
async down(db) {
|
|
384
|
+
await db.query(\`
|
|
385
|
+
ALTER TABLE users
|
|
386
|
+
DROP COLUMN avatar_url,
|
|
387
|
+
DROP COLUMN bio,
|
|
388
|
+
DROP COLUMN created_at
|
|
389
|
+
\`);
|
|
390
|
+
console.log('✅ User profiles removed');
|
|
391
|
+
}
|
|
392
|
+
};
|
|
393
|
+
```
|
|
394
|
+
|
|
395
|
+
### 📊 Supported Adapters
|
|
396
|
+
|
|
397
|
+
| Database | Status | Cache Support | Increment/Decrement | Migrations |
|
|
398
|
+
|----------|--------|---------------|---------------------|------------|
|
|
399
|
+
| SQLite | ✅ Full | ✅ Memory/Redis | ✅ Native SQL | ✅ Yes |
|
|
400
|
+
| MySQL | ✅ Full | ✅ Memory/Redis | ✅ Native SQL | ✅ Yes |
|
|
401
|
+
| PostgreSQL | ✅ Full | ✅ Memory/Redis | ✅ Native SQL | ✅ Yes |
|
|
402
|
+
| MongoDB | ✅ Full | ✅ Memory/Redis | ✅ $inc operator | ✅ Yes |
|
|
403
|
+
| Redis | ✅ Full | ✅ Memory/Redis | ✅ HINCRBY | ✅ Yes |
|
|
404
|
+
| JSON File | ✅ Full | ✅ Memory/Redis | ✅ JavaScript | ✅ Yes |
|
|
405
|
+
|
|
406
|
+
---
|
|
407
|
+
|
|
408
|
+
## 💡 Examples
|
|
409
|
+
|
|
410
|
+
### Real-World E-commerce Example
|
|
411
|
+
|
|
412
|
+
```javascript
|
|
413
|
+
const createDatabase = require('@onurege3467/zerohelper/database');
|
|
414
|
+
const helpers = require('@onurege3467/zerohelper/functions');
|
|
415
|
+
|
|
416
|
+
class EcommerceService {
|
|
417
|
+
constructor() {
|
|
418
|
+
this.db = createDatabase({
|
|
419
|
+
adapter: 'mysql',
|
|
420
|
+
config: {
|
|
421
|
+
host: 'localhost',
|
|
422
|
+
user: 'ecommerce_user',
|
|
423
|
+
password: process.env.DB_PASSWORD,
|
|
424
|
+
database: 'ecommerce',
|
|
425
|
+
cache: { type: 'redis', host: 'redis', ttl: 600 }
|
|
426
|
+
}
|
|
427
|
+
});
|
|
428
|
+
|
|
429
|
+
this.logger = helpers.logger.createLogger({
|
|
430
|
+
level: 'info',
|
|
431
|
+
logFile: './ecommerce.log'
|
|
432
|
+
});
|
|
433
|
+
}
|
|
434
|
+
|
|
435
|
+
async createUser(userData) {
|
|
436
|
+
// Validate input
|
|
437
|
+
const schema = {
|
|
438
|
+
email: { required: true, pattern: /^[^\s@]+@[^\s@]+\.[^\s@]+$/ },
|
|
439
|
+
password: { required: true, minLength: 8 },
|
|
440
|
+
name: { required: true, minLength: 2 }
|
|
441
|
+
};
|
|
442
|
+
|
|
443
|
+
const validation = helpers.validation.validateSchema(userData, schema);
|
|
444
|
+
if (!validation.isValid) {
|
|
445
|
+
throw new Error(\`Validation failed: \${validation.errors.join(', ')}\`);
|
|
446
|
+
}
|
|
447
|
+
|
|
448
|
+
// Security
|
|
449
|
+
if (!helpers.crypto.isPasswordStrong(userData.password)) {
|
|
450
|
+
throw new Error('Password must be stronger');
|
|
451
|
+
}
|
|
452
|
+
|
|
453
|
+
// Create user
|
|
454
|
+
const hashedPassword = helpers.crypto.hashPassword(userData.password);
|
|
455
|
+
const userId = await this.db.insert('users', {
|
|
456
|
+
id: helpers.random.makeUniqueId(),
|
|
457
|
+
email: userData.email,
|
|
458
|
+
name: helpers.validation.sanitizeInput(userData.name),
|
|
459
|
+
password: hashedPassword,
|
|
460
|
+
created_at: new Date()
|
|
461
|
+
});
|
|
462
|
+
|
|
463
|
+
this.logger.info('User created successfully', { userId, email: userData.email });
|
|
464
|
+
return userId;
|
|
465
|
+
}
|
|
466
|
+
|
|
467
|
+
async addToCart(userId, productId, quantity) {
|
|
468
|
+
// Check stock availability
|
|
469
|
+
const product = await this.db.selectOne('products', { id: productId });
|
|
470
|
+
if (!product || product.stock < quantity) {
|
|
471
|
+
throw new Error('Insufficient stock');
|
|
472
|
+
}
|
|
473
|
+
|
|
474
|
+
// Add to cart and update stock atomically
|
|
475
|
+
await this.db.set('cart_items',
|
|
476
|
+
{ user_id: userId, product_id: productId, quantity },
|
|
477
|
+
{ user_id: userId, product_id: productId }
|
|
478
|
+
);
|
|
479
|
+
|
|
480
|
+
await this.db.decrement('products', { stock: quantity }, { id: productId });
|
|
481
|
+
await this.db.increment('products', { times_ordered: 1 }, { id: productId });
|
|
482
|
+
|
|
483
|
+
this.logger.info('Product added to cart', { userId, productId, quantity });
|
|
484
|
+
}
|
|
485
|
+
|
|
486
|
+
async getPopularProducts(limit = 10) {
|
|
487
|
+
// This will be cached automatically
|
|
488
|
+
return await this.db.select('products', {}, {
|
|
489
|
+
orderBy: 'times_ordered DESC',
|
|
490
|
+
limit
|
|
491
|
+
});
|
|
492
|
+
}
|
|
493
|
+
}
|
|
494
|
+
```
|
|
495
|
+
|
|
496
|
+
### Analytics Dashboard Example
|
|
497
|
+
|
|
498
|
+
```javascript
|
|
499
|
+
class AnalyticsService {
|
|
500
|
+
constructor() {
|
|
501
|
+
this.db = createDatabase({
|
|
502
|
+
adapter: 'postgres',
|
|
503
|
+
config: {
|
|
504
|
+
host: process.env.PG_HOST,
|
|
505
|
+
database: 'analytics',
|
|
506
|
+
cache: { type: 'memory', max: 2000, ttl: 180000 } // 3 minutes
|
|
507
|
+
}
|
|
508
|
+
});
|
|
509
|
+
}
|
|
510
|
+
|
|
511
|
+
async trackPageView(data) {
|
|
512
|
+
const today = new Date().toISOString().split('T')[0];
|
|
513
|
+
|
|
514
|
+
// Validate and sanitize
|
|
515
|
+
const cleanData = {
|
|
516
|
+
page: helpers.validation.sanitizeInput(data.page),
|
|
517
|
+
user_agent: helpers.validation.sanitizeInput(data.userAgent),
|
|
518
|
+
ip: data.ip,
|
|
519
|
+
referrer: helpers.validation.sanitizeInput(data.referrer)
|
|
520
|
+
};
|
|
521
|
+
|
|
522
|
+
// Track multiple metrics atomically
|
|
523
|
+
await this.db.increment('daily_stats', {
|
|
524
|
+
page_views: 1,
|
|
525
|
+
unique_visitors: data.isUnique ? 1 : 0,
|
|
526
|
+
bounce_rate: data.bounced ? 1 : 0
|
|
527
|
+
}, { date: today, page: cleanData.page });
|
|
528
|
+
|
|
529
|
+
// Track real-time metrics
|
|
530
|
+
await this.db.increment('realtime_stats', {
|
|
531
|
+
current_visitors: 1
|
|
532
|
+
}, { page: cleanData.page });
|
|
533
|
+
|
|
534
|
+
helpers.logger.info('Page view tracked', cleanData);
|
|
535
|
+
}
|
|
536
|
+
|
|
537
|
+
async getDashboardData(dateRange) {
|
|
538
|
+
const [dailyStats, topPages, realtime] = await Promise.all([
|
|
539
|
+
this.db.select('daily_stats', {
|
|
540
|
+
date: { $gte: dateRange.start, $lte: dateRange.end }
|
|
541
|
+
}),
|
|
542
|
+
this.db.select('daily_stats', {}, {
|
|
543
|
+
orderBy: 'page_views DESC',
|
|
544
|
+
limit: 10
|
|
545
|
+
}),
|
|
546
|
+
this.db.select('realtime_stats')
|
|
547
|
+
]);
|
|
548
|
+
|
|
549
|
+
return { dailyStats, topPages, realtime };
|
|
550
|
+
}
|
|
551
|
+
}
|
|
552
|
+
```
|
|
553
|
+
|
|
554
|
+
---
|
|
555
|
+
|
|
556
|
+
## 🔧 API Reference
|
|
557
|
+
|
|
558
|
+
### Database Operations
|
|
559
|
+
|
|
560
|
+
#### Basic CRUD
|
|
561
|
+
```javascript
|
|
562
|
+
// Create
|
|
563
|
+
const id = await db.insert('table', data);
|
|
564
|
+
const count = await db.bulkInsert('table', dataArray);
|
|
565
|
+
|
|
566
|
+
// Read
|
|
567
|
+
const rows = await db.select('table', whereConditions);
|
|
568
|
+
const row = await db.selectOne('table', whereConditions);
|
|
569
|
+
|
|
570
|
+
// Update
|
|
571
|
+
const affected = await db.update('table', newData, whereConditions);
|
|
572
|
+
const result = await db.set('table', data, whereConditions); // Upsert
|
|
573
|
+
|
|
574
|
+
// Delete
|
|
575
|
+
const deleted = await db.delete('table', whereConditions);
|
|
576
|
+
```
|
|
577
|
+
|
|
578
|
+
#### Advanced Operations
|
|
579
|
+
```javascript
|
|
580
|
+
// Atomic increment/decrement
|
|
581
|
+
await db.increment('table', { field1: amount1, field2: amount2 }, where);
|
|
582
|
+
await db.decrement('table', { field1: amount1, field2: amount2 }, where);
|
|
583
|
+
|
|
584
|
+
// Cache management
|
|
585
|
+
db.clearAllCache();
|
|
586
|
+
const stats = db.getCacheStats();
|
|
587
|
+
|
|
588
|
+
// Connection management
|
|
589
|
+
await db.close();
|
|
590
|
+
```
|
|
591
|
+
|
|
592
|
+
### Utility Functions
|
|
593
|
+
|
|
594
|
+
#### Random & Generation
|
|
595
|
+
```javascript
|
|
596
|
+
helpers.random.makeUniqueId() // Unique ID
|
|
597
|
+
helpers.random.randomArray(array) // Random array element
|
|
598
|
+
helpers.random.randomText(length) // Random string
|
|
599
|
+
helpers.random.randomNumber(min, max) // Random integer
|
|
600
|
+
helpers.random.randomFloat(min, max) // Random float
|
|
601
|
+
helpers.random.randomEmoji() // Random emoji
|
|
602
|
+
helpers.random.randomHex() // Random hex color
|
|
603
|
+
```
|
|
604
|
+
|
|
605
|
+
#### Validation & Security
|
|
606
|
+
```javascript
|
|
607
|
+
helpers.validation.isEmail(email) // Email validation
|
|
608
|
+
helpers.validation.isPhone(phone) // Phone validation
|
|
609
|
+
helpers.validation.isURL(url) // URL validation
|
|
610
|
+
helpers.validation.sanitizeHTML(html) // HTML sanitization
|
|
611
|
+
helpers.validation.validateCreditCard(number) // Credit card validation
|
|
612
|
+
helpers.validation.validateSchema(data, schema) // Schema validation
|
|
613
|
+
helpers.validation.sanitizeInput(input, options) // Input sanitization
|
|
614
|
+
|
|
615
|
+
helpers.crypto.hashPassword(password) // Hash password
|
|
616
|
+
helpers.crypto.verifyPassword(password, hash) // Verify password
|
|
617
|
+
helpers.crypto.encryptText(text, secret) // Encrypt data
|
|
618
|
+
helpers.crypto.decryptText(encrypted, secret, iv) // Decrypt data
|
|
619
|
+
helpers.crypto.generateJWT(payload, secret) // Generate JWT
|
|
620
|
+
helpers.crypto.verifyJWT(token, secret) // Verify JWT
|
|
621
|
+
```
|
|
622
|
+
|
|
623
|
+
#### Data Manipulation
|
|
624
|
+
```javascript
|
|
625
|
+
helpers.array.shuffleArray(array) // Shuffle array
|
|
626
|
+
helpers.array.flattenArray(array) // Flatten nested array
|
|
627
|
+
helpers.array.groupBy(array, key) // Group array by key
|
|
628
|
+
helpers.array.pluck(array, key) // Extract property values
|
|
629
|
+
helpers.array.sortBy(array, key) // Sort array by property
|
|
630
|
+
|
|
631
|
+
helpers.object.filterObjectByKey(obj, keys) // Filter object properties
|
|
632
|
+
helpers.object.deepMerge(obj1, obj2) // Deep merge objects
|
|
633
|
+
|
|
634
|
+
helpers.string.titleCase(string) // Convert to title case
|
|
635
|
+
helpers.string.generateSlug(string) // Generate URL slug
|
|
636
|
+
helpers.string.wordCount(string) // Count words
|
|
637
|
+
```
|
|
638
|
+
|
|
639
|
+
#### Math & Statistics
|
|
640
|
+
```javascript
|
|
641
|
+
helpers.math.mean(array) // Calculate average
|
|
642
|
+
helpers.math.median(array) // Calculate median
|
|
643
|
+
helpers.math.variance(array) // Calculate variance
|
|
644
|
+
helpers.math.standardDeviation(array) // Calculate std deviation
|
|
645
|
+
helpers.math.sum(array) // Sum array values
|
|
646
|
+
helpers.math.max(array) // Find maximum
|
|
647
|
+
helpers.math.min(array) // Find minimum
|
|
648
|
+
helpers.math.range(start, end) // Generate number range
|
|
649
|
+
helpers.math.isPrime(number) // Check if prime
|
|
650
|
+
```
|
|
651
|
+
|
|
652
|
+
---
|
|
653
|
+
|
|
654
|
+
## ⚡ Performance Tips
|
|
655
|
+
|
|
656
|
+
### Database Optimization
|
|
657
|
+
1. **Use Caching**: Enable memory or Redis cache for frequently accessed data
|
|
658
|
+
2. **Batch Operations**: Use \`bulkInsert\` for multiple records
|
|
659
|
+
3. **Smart Queries**: Leverage where conditions to minimize data transfer
|
|
660
|
+
4. **Index Strategy**: Create proper database indexes for your queries
|
|
661
|
+
|
|
662
|
+
### Cache Strategy
|
|
663
|
+
```javascript
|
|
664
|
+
// High-traffic read operations
|
|
665
|
+
const db = createDatabase({
|
|
666
|
+
adapter: 'mysql',
|
|
667
|
+
config: {
|
|
668
|
+
// ... connection config
|
|
669
|
+
cache: {
|
|
670
|
+
type: 'redis',
|
|
671
|
+
max: 10000,
|
|
672
|
+
ttl: 3600, // 1 hour for static data
|
|
673
|
+
updateAgeOnGet: true
|
|
674
|
+
}
|
|
675
|
+
}
|
|
676
|
+
});
|
|
677
|
+
|
|
678
|
+
// Frequent increment operations benefit from smart cache
|
|
679
|
+
await db.increment('counters', { views: 1 }, { page_id: 123 }); // No cache miss!
|
|
680
|
+
```
|
|
681
|
+
|
|
682
|
+
---
|
|
683
|
+
|
|
684
|
+
## 🔧 Configuration
|
|
685
|
+
|
|
686
|
+
### Environment Variables
|
|
687
|
+
```bash
|
|
688
|
+
# Database
|
|
689
|
+
DB_HOST=localhost
|
|
690
|
+
DB_USER=myuser
|
|
691
|
+
DB_PASSWORD=mypassword
|
|
692
|
+
DB_NAME=mydatabase
|
|
693
|
+
|
|
694
|
+
# Redis Cache
|
|
695
|
+
REDIS_HOST=localhost
|
|
696
|
+
REDIS_PORT=6379
|
|
697
|
+
REDIS_PASSWORD=redispassword
|
|
698
|
+
|
|
699
|
+
# Security
|
|
700
|
+
JWT_SECRET=your-super-secret-key
|
|
701
|
+
ENCRYPTION_KEY=your-encryption-key
|
|
702
|
+
|
|
703
|
+
# Logging
|
|
704
|
+
LOG_LEVEL=info
|
|
705
|
+
LOG_FILE=./app.log
|
|
706
|
+
```
|
|
707
|
+
|
|
708
|
+
---
|
|
709
|
+
|
|
710
|
+
## 🐛 Troubleshooting
|
|
711
|
+
|
|
712
|
+
### Common Issues
|
|
713
|
+
|
|
714
|
+
#### Cache Connection Issues
|
|
715
|
+
```javascript
|
|
716
|
+
// Handle Redis connection failures gracefully
|
|
717
|
+
const db = createDatabase({
|
|
718
|
+
adapter: 'mysql',
|
|
719
|
+
config: {
|
|
720
|
+
// ... mysql config
|
|
721
|
+
cache: {
|
|
722
|
+
type: 'redis',
|
|
723
|
+
host: 'redis-server',
|
|
724
|
+
// Fallback to memory cache on Redis failure
|
|
725
|
+
fallbackToMemory: true
|
|
726
|
+
}
|
|
727
|
+
}
|
|
728
|
+
});
|
|
729
|
+
```
|
|
730
|
+
|
|
731
|
+
#### Debug Mode
|
|
732
|
+
```javascript
|
|
733
|
+
// Enable detailed logging
|
|
734
|
+
const logger = helpers.logger.createLogger({
|
|
735
|
+
level: 'debug',
|
|
736
|
+
enableColors: true,
|
|
737
|
+
logFile: './debug.log'
|
|
738
|
+
});
|
|
739
|
+
|
|
740
|
+
// Monitor cache performance
|
|
741
|
+
setInterval(() => {
|
|
742
|
+
console.log('Cache Stats:', db.getCacheStats());
|
|
743
|
+
}, 30000);
|
|
744
|
+
```
|
|
745
|
+
|
|
746
|
+
---
|
|
747
|
+
|
|
748
|
+
## 🙏 Acknowledgments
|
|
749
|
+
|
|
750
|
+
- Built with ❤️ by [Onure9e](https://github.com/onure9e)
|
|
751
|
+
- Inspired by the need for a comprehensive, production-ready JavaScript toolkit
|
|
752
|
+
- Special thanks to the open-source community
|
|
753
|
+
|
|
754
|
+
---
|
|
755
|
+
|
|
756
|
+
<div align="center">
|
|
757
|
+
|
|
758
|
+
**[⭐ Star this repository](https://github.com/onure9e/zerohelper) if ZeroHelper helped you build something amazing!**
|
|
759
|
+
|
|
760
|
+
Made with 💻 and ☕ by developers, for developers.
|
|
761
|
+
|
|
762
|
+
</div>
|