@onurege3467/zerohelper 5.0.3 → 6.0.1

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.
Files changed (62) hide show
  1. package/data/test_db.json +3 -0
  2. package/data/test_db.sqlite +0 -0
  3. package/data/test_db_cached.sqlite +0 -0
  4. package/database/cacheWrapper.js +121 -0
  5. package/database/index.js +24 -6
  6. package/database/{adapters/json.js → json.js} +9 -9
  7. package/database/{adapters/mongodb.js → mongodb.js} +1 -0
  8. package/database/{adapters/mysql.js → mysql.js} +12 -12
  9. package/database/{adapters/sqlite.js → sqlite.js} +86 -77
  10. package/functions/index.js +14 -4
  11. package/package.json +4 -3
  12. package/readme.md +111 -324
  13. package/test.js +244 -0
  14. package/database/csvdb/index.js +0 -90
  15. package/database/jsondatabase/index.js +0 -132
  16. package/database/migrate/index.js +0 -68
  17. package/database/mongodb/index.js +0 -49
  18. package/database/mongodb/src/client/Client.js +0 -37
  19. package/database/mongodb/src/structers/Collection.js +0 -136
  20. package/database/mongodb/src/structers/Data.js +0 -282
  21. package/database/mongodb/src/structers/Database.js +0 -53
  22. package/database/mongodb/src/tools/FormatTool.js +0 -5
  23. package/database/mysql/examples/example.js +0 -301
  24. package/database/mysql/index.js +0 -1
  25. package/database/mysql/structures/classes/MySQL.js +0 -41
  26. package/database/mysql/structures/errors/strings.js +0 -23
  27. package/database/mysql/structures/methods/add.js +0 -19
  28. package/database/mysql/structures/methods/all.js +0 -25
  29. package/database/mysql/structures/methods/auto_increment.js +0 -16
  30. package/database/mysql/structures/methods/base_get.js +0 -14
  31. package/database/mysql/structures/methods/base_set.js +0 -21
  32. package/database/mysql/structures/methods/clear.js +0 -16
  33. package/database/mysql/structures/methods/connect.js +0 -15
  34. package/database/mysql/structures/methods/create.js +0 -11
  35. package/database/mysql/structures/methods/create_db.js +0 -10
  36. package/database/mysql/structures/methods/delete.js +0 -31
  37. package/database/mysql/structures/methods/drop.js +0 -13
  38. package/database/mysql/structures/methods/end.js +0 -7
  39. package/database/mysql/structures/methods/exists.js +0 -15
  40. package/database/mysql/structures/methods/get.js +0 -40
  41. package/database/mysql/structures/methods/getAllData.js +0 -35
  42. package/database/mysql/structures/methods/has.js +0 -42
  43. package/database/mysql/structures/methods/includes.js +0 -17
  44. package/database/mysql/structures/methods/ping.js +0 -11
  45. package/database/mysql/structures/methods/process.js +0 -7
  46. package/database/mysql/structures/methods/pull.js +0 -23
  47. package/database/mysql/structures/methods/push.js +0 -23
  48. package/database/mysql/structures/methods/query.js +0 -9
  49. package/database/mysql/structures/methods/rename.js +0 -16
  50. package/database/mysql/structures/methods/set.js +0 -60
  51. package/database/mysql/structures/methods/stats.js +0 -13
  52. package/database/mysql/structures/methods/sub.js +0 -19
  53. package/database/mysql/structures/methods/tables.js +0 -8
  54. package/database/mysql/structures/methods/variables.js +0 -20
  55. package/database/newMongoDB/index.js +0 -94
  56. package/database/newMySQL/index.js +0 -205
  57. package/database/newSQLite/index.js +0 -240
  58. package/database/postgresql/index.js +0 -150
  59. package/database/redis/index.js +0 -125
  60. package/database/sqldb/index.js +0 -243
  61. package/database/yamldatabase/index.js +0 -76
  62. /package/database/{adapters/IDatabase.js → IDatabase.js} +0 -0
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@onurege3467/zerohelper",
3
- "version": "5.0.3",
3
+ "version": "6.0.1",
4
4
  "main": "index.js",
5
5
  "scripts": {
6
6
  "test": "node test.js"
@@ -26,7 +26,7 @@
26
26
  "description": "ZeroHelper is a versatile JavaScript library offering helper functions and database utilities for developers. It supports MongoDB, MySQL, SQLite, Redis, and PostgreSQL.",
27
27
  "dependencies": {
28
28
  "bcrypt": "^5.1.1",
29
- "better-sqlite3": "^11.10.0",
29
+
30
30
  "crypto": "^1.0.1",
31
31
  "csv": "^6.3.11",
32
32
  "dotenv": "^16.4.7",
@@ -40,6 +40,7 @@
40
40
  "pg": "^8.14.1",
41
41
  "promise-mysql": "^5.2.0",
42
42
  "redis": "^4.7.0",
43
- "sqlite3": "^5.1.7"
43
+ "sqlite3": "^5.1.7",
44
+ "lru-cache": "^10.0.0"
44
45
  }
45
46
  }
package/readme.md CHANGED
@@ -15,14 +15,8 @@ ZeroHelper is a versatile JavaScript package providing helper functions and data
15
15
  - [🔒 Crypto Functions](#crypto-functions-)
16
16
  - [➗ Math Functions](#math-functions-)
17
17
  3. [💾 Database Utilities](#-database-utilities)
18
- - [🗃️ JsonDatabase](#jsondatabase-️)
19
- - [♦️ YamlDatabase](#yamldatabase-️)
20
- - [🎋 CSV Database](#csv-database-)
21
- - [🗄️ MongoDB](#mongodb-️)
22
- - [🐬 MySQL](#mysql-)
23
- - [📱 SQLiteDB](#sqlitedb-)
24
- - [🍇 PostgreSQL](#postgresql-)
25
- - [⚡ Redis](#redis-)
18
+ - [🏭 Using the Database Factory](#-using-the-database-factory)
19
+ - [📚 API Reference](#-api-reference)
26
20
  4. [🔄 Database Migration](#database-migration)
27
21
 
28
22
  ---
@@ -166,240 +160,149 @@ console.log(prime); // true
166
160
 
167
161
  ZeroHelper provides multiple database utilities for seamless integration with various databases.
168
162
 
169
- # JsonDatabase 🗃️
163
+ ## 💾 Using ZeroHelper as Database
170
164
 
171
- ```js
172
- (async function () {
173
- const JsonDatabase = require("@onurege3467/zerohelper/database/jsondatabase");
174
- const db = new JsonDatabase();
165
+ ZeroHelper provides a flexible database factory for seamless integration with various databases.
175
166
 
176
- await db.set("foo", "bar");
177
- await db.push("array", "x");
178
- await db.delete("foo");
167
+ ### 🏭 Using the Database Factory
179
168
 
180
- await db.add("number", 1);
181
- await db.sub("number", 1);
169
+ ZeroHelper's database factory allows you to create database instances with various adapters. You can also enable and configure an LRU (Least Recently Used) cache for read operations to improve performance.
182
170
 
183
- await console.log(db.get("foo"));
184
- await console.log(db.has("foo"));
185
- })();
186
- ```
187
- # YamlDatabase 🗃️
188
- ```js
189
- (async function () {
190
- const YamlDatabase = require("@onurege3467/zerohelper/database/yamldatabase");
191
- const db = new YamlDatabase();
171
+ #### Enabling and Configuring Cache
192
172
 
193
- await db.set("foo", "bar");
194
- await db.push("array", "x");
195
- await db.delete("foo");
173
+ To enable caching, pass a `cache` object within the `config` object when creating a database instance. The `cache` object can have the following properties:
196
174
 
197
- await db.add("number", 1);
198
- await db.sub("number", 1);
175
+ - `max`: (Number, optional) The maximum number of items to store in the cache. Defaults to `500`.
176
+ - `ttl`: (Number, optional) The time to live for cache entries in milliseconds. Defaults to `300000` (5 minutes).
177
+ - `updateAgeOnGet`: (Boolean, optional) If `true`, accessing an item refreshes its `ttl`. Defaults to `false`.
199
178
 
200
- await console.log(db.get("foo"));
201
- await console.log(db.has("foo"));
202
- })();
203
- ```
204
- # CSV Database 🎋
205
- ```js
206
- (async function () {
207
- const csvdb = require("@onurege3467/zerohelper/database/csvdb");
208
- const db = new csvdb();
179
+ **Example with Cache Enabled:**
209
180
 
210
- await db.set("foo", "bar");
211
- await db.push("array", "x");
212
- await db.delete("foo");
213
-
214
- await db.add("number", 1);
215
- await db.sub("number", 1);
181
+ ```javascript
182
+ const path = require('path');
183
+ const createDatabase = require('@onurege3467/zerohelper/database');
216
184
 
217
- await console.log(db.get("foo"));
218
- await console.log(db.has("foo"));
219
- })();
220
- ```
221
- # MongoDB 🗄️
185
+ const cachedSqliteDb = createDatabase({
186
+ adapter: 'sqlite',
187
+ config: {
188
+ filePath: path.join(__dirname, 'data', 'cached_development.sqlite'),
189
+ cache: {
190
+ max: 1000, // Cache up to 1000 items
191
+ ttl: 1000 * 60 * 10, // Cache items for 10 minutes
192
+ updateAgeOnGet: true // Refresh TTL on access
193
+ }
194
+ }
195
+ });
222
196
 
223
- ```js
224
- (async function () {
225
- const MongoDB = require("@onurege3467/zerohelper/database/mongodb");
226
- const db = await MongoDB.createData(
227
- "database",
228
- "collection",
229
- "data",
230
- undefined,
231
- "mongourl"
232
- );
233
-
234
- await db.set("foo", "bar");
235
- await db.push("array", "x");
236
- await db.delete("foo");
237
-
238
- await db.add("number", 1);
239
- await db.sub("number", 1);
240
-
241
- console.log(await db.get("foo"));
242
- console.log(await db.has("foo"));
243
-
244
- console.log(await db.ping());
245
- })();
197
+ // Subsequent `select` or `selectOne` calls for the same query will hit the cache
198
+ // Write operations (insert, update, delete, set, bulkInsert) will automatically invalidate the cache for the affected table.
246
199
  ```
247
200
 
248
- # MySQL 🐬
249
-
250
- ```js
251
- (async function () {
252
- const MySQL = require("@onurege3467/zerohelper/database/mysql");
253
-
254
- const db = new MySQL();
255
- await db.connect({
256
- host: "localhost",
257
- port: "3306",
258
- user: "root",
259
- password: "",
260
- database: "database",
261
- charset: "utf8mb4",
262
- });
263
-
264
- db.on("connected", async () => {
265
- console.log("Database Connected");
266
- });
267
-
268
- await db.set("key", "value"); // Uses the default table
269
- await db.set("key", "value", "custom_table"); // Uses the specified table
270
-
271
- const value = await db.get("key"); // Uses the default table
272
- const valueInCustomTable = await db.get("key", "custom_table"); // Uses the specified table
273
-
274
- await db.add("count", 10); // Uses the default table
275
- await db.add("count", 10, "custom_table"); // Uses the specified table
276
-
277
- await db.sub("count", 5); // Uses the default table
278
- await db.sub("count", 5, "custom_table"); // Uses the specified table
279
-
280
- await db.push("array", "value"); // Uses the default table
281
- await db.push("array", "value", "custom_table"); // Uses the specified table
282
-
283
- await db.pull("array", "value"); // Uses the default table
284
- await db.pull("array", "value", "custom_table"); // Uses the specified table
201
+ **Basic Usage (without cache configuration shown):**
285
202
 
286
- await db.delete("key"); // Uses the default table
287
- await db.delete("key", "custom_table"); // Uses the specified table
288
-
289
- const exists = await db.exists("key"); // Uses the default table
290
- const existsInCustomTable = await db.exists("key", "custom_table"); // Uses the specified table
291
-
292
- const includes = await db.includes("array", "value"); // Uses the default table
293
- const includesInCustomTable = await db.includes(
294
- "array",
295
- "value",
296
- "custom_table"
297
- ); // Uses the specified table
298
-
299
- const allData = await db.all(); // Uses the default table
300
- const allDataInCustomTable = await db.all("custom_table"); // Uses the specified table
301
-
302
- await db.clear(); // Clears the default table
303
- await db.clear("custom_table"); // Clears the specified table
203
+ ```javascript
204
+ const path = require('path');
205
+ const createDatabase = require('@onurege3467/zerohelper/database'); // Adjust the path to your project structure
304
206
 
305
- await db.drop(); // Drops the default table
306
- await db.drop("custom_table"); // Drops the specified table
207
+ // --- 1. Using SQLite (Fast and Lightweight) ---
208
+ const sqliteDb = createDatabase({
209
+ adapter: 'sqlite',
210
+ config: {
211
+ filePath: path.join(__dirname, 'data', 'development.sqlite')
212
+ }
213
+ });
307
214
 
308
- await db.rename("old_table", "new_table");
215
+ // --- 2. Using MySQL (For Production) ---
216
+ const mysqlDb = createDatabase({
217
+ adapter: 'mysql',
218
+ config: {
219
+ host: 'localhost',
220
+ user: 'root',
221
+ password: 'your_password',
222
+ database: 'my_app_prod'
223
+ }
224
+ });
309
225
 
310
- const ping = await db.ping();
311
- console.log(`Ping: ${ping}ms`);
226
+ // --- 3. Using a JSON File (For Simple Prototyping) ---
227
+ const jsonDb = createDatabase({
228
+ adapter: 'json',
229
+ config: {
230
+ filePath: path.join(__dirname, 'data', 'db.json')
231
+ }
232
+ });
312
233
 
313
- // Sets MySQL global variables
314
- await db.variables({
315
- max_connections: 100000,
316
- wait_timeout: 60,
317
- });
318
- })();
234
+ // --- 4. Using MongoDB ---
235
+ const mongoDb = createDatabase({
236
+ adapter: 'mongodb',
237
+ config: {
238
+ url: 'mongodb://localhost:27017',
239
+ database: 'my_app_mongo'
240
+ }
241
+ });
319
242
  ```
320
243
 
321
- # SQLiteDB 📱
322
-
323
- ```js
324
- (async function () {
325
- const SQLiteDB = require("@onurege3467/zerohelper/database/sqldb");
326
-
327
- const db = new SQLiteDB();
328
-
329
- await db.set("foo", "bar");
330
- await db.push("array", "x");
331
- await db.delete("foo");
332
-
333
- await db.add("number", 1);
334
- await db.sub("number", 1);
335
-
336
- console.log(await db.get("foo"));
337
- console.log(await db.has("foo"));
338
- })();
339
- ```
244
+ ### Basic Operations (CRUD)
340
245
 
341
- # PostgreSQL 🍇
246
+ No matter which adapter you choose, you can use the following methods in exactly the same way.
342
247
 
343
- ```js
344
- (async function () {
345
- const PostgreSQL = require("@onurege3467/zerohelper/database/postgresql");
346
-
347
- const db = new PostgreSQL({
348
- user: "your_username",
349
- host: "localhost",
350
- database: "your_database",
351
- password: "your_password",
352
- port: 5432,
248
+ ```javascript
249
+ async function main() {
250
+ // Let's use sqliteDb for this example
251
+ const db = createDatabase({
252
+ adapter: 'sqlite',
253
+ config: { filePath: 'app.db' }
353
254
  });
354
255
 
355
- await db.set("foo", "bar");
356
- console.log(await db.get("foo"));
357
- console.log(await db.has("foo"));
358
- await db.delete("foo");
359
-
360
- await db.add("number", 10);
361
- await db.sub("number", 5);
362
-
363
- await db.set("array", []);
364
- await db.push("array", "value");
365
- console.log(await db.get("array"));
256
+ try {
257
+ // Insert Data
258
+ const newUserId = await db.insert('users', { name: 'John Doe', email: 'john@example.com', age: 30 });
259
+ console.log(`New user added with ID: ${newUserId}`);
366
260
 
367
- console.log(await db.ping());
261
+ // Select Data
262
+ const user = await db.selectOne('users', { name: 'John Doe' });
263
+ console.log('Found user:', user);
368
264
 
369
- await db.close();
370
- })();
371
- ```
265
+ // Update Data
266
+ await db.update('users', { age: 31 }, { email: 'john@example.com' });
267
+ console.log('User updated.');
372
268
 
373
- # Redis
269
+ // Update if exists, or insert if not (Upsert)
270
+ await db.set('users', { city: 'New York' }, { name: 'John Doe' }); // Updates existing
271
+ await db.set('users', { name: 'Jane Doe', email: 'jane@example.com' }, { name: 'Jane Doe' }); // Inserts new
374
272
 
375
- ```js
376
- (async function () {
377
- const RedisDatabase = require("@onurege3467/zerohelper/database/redis");
273
+ // Select All Data
274
+ const allUsers = await db.select('users');
275
+ console.log('All users:', allUsers);
378
276
 
379
- const db = new RedisDatabase({
380
- url: "redis://localhost:6379",
381
- });
277
+ // Delete Data
278
+ await db.delete('users', { name: 'John Doe' });
279
+ console.log('User deleted.');
382
280
 
383
- await db.connect();
281
+ } catch (error) {
282
+ console.error('An error occurred:', error);
283
+ } finally {
284
+ // Close the connection
285
+ await db.close();
286
+ }
287
+ }
384
288
 
385
- await db.set("user.name", "John Doe");
386
- console.log(await db.get("user.name"));
387
- console.log(await db.has("user.name"));
388
- await db.delete("user.name");
289
+ main();
290
+ ```
389
291
 
390
- await db.add("stats.score", 10);
391
- await db.sub("stats.score", 5);
292
+ ### 📚 API Reference
392
293
 
393
- await db.set("items", []);
394
- await db.push("items", "item1");
395
- console.log(await db.get("items"));
294
+ All adapters implement the following common methods (the `IDatabase` interface):
396
295
 
397
- console.log(await db.ping());
296
+ - `select(table, where)`: Returns an array of all rows matching the query.
297
+ - `selectOne(table, where)`: Returns the first row matching the query as an object, or `null`.
298
+ - `insert(table, data)`: Inserts a new row and returns its ID.
299
+ - `update(table, data, where)`: Updates rows matching the query and returns the number of affected rows.
300
+ - `delete(table, where)`: Deletes rows matching the query and returns the number of affected rows.
301
+ - `set(table, data, where)`: Updates a record if it exists, otherwise inserts it as a new record.
302
+ - `bulkInsert(table, dataArray)`: Inserts an array of objects in a single, optimized operation.
303
+ - `close()`: Safely closes the database connection or file handle.
398
304
 
399
- await db.close();
400
- })();
401
- ```
402
- ## Schema DB
305
+ ## Database Migration
403
306
 
404
307
  ```javascript
405
308
  const path = require('path');
@@ -502,119 +405,3 @@ All adapters implement the following common methods (the `IDatabase` interface):
502
405
  - `set(table, data, where)`: Updates a record if it exists, otherwise inserts it as a new record.
503
406
  - `bulkInsert(table, dataArray)`: Inserts an array of objects in a single, optimized operation.
504
407
  - `close()`: Safely closes the database connection or file handle.
505
-
506
- ## Database Migration
507
-
508
- The `migrateData` function allows you to migrate data between different types of databases. It supports JSON, MongoDB, MySQL, SQLite, Redis, and PostgreSQL.
509
-
510
- # Example: Migrate Data from JSON to MongoDB
511
-
512
- ```js
513
- const migrateData = require("@onurege3467/zerohelper/database/migrate");
514
-
515
- const sourceConfig = {
516
- type: "json",
517
- options: {
518
- filePath: "databases/source.json", // Path to the JSON file
519
- },
520
- };
521
-
522
- const targetConfig = {
523
- type: "mongodb",
524
- options: {
525
- url: "mongodb://localhost:27017", // MongoDB connection URL
526
- database: "targetDatabase", // Target database name
527
- collection: "targetCollection", // Target collection name
528
- },
529
- };
530
-
531
- (async () => {
532
- try {
533
- await migrateData(sourceConfig, targetConfig);
534
- console.log("Data migration completed successfully!");
535
- } catch (error) {
536
- console.error("Error during migration:", error);
537
- }
538
- })();
539
- ```
540
-
541
- # Supported Database Types and Options
542
-
543
- ```json
544
- {
545
- "type": "json",
546
- "options": {
547
- "filePath": "path/to/json/file.json"
548
- }
549
- }
550
- ```
551
- ```json
552
- {
553
- "type": "yaml",
554
- "options": {
555
- "filePath": "data.yaml"
556
- }
557
- }
558
- ```
559
- ```json
560
- {
561
- "type": "csv",
562
- "options": {
563
- "filePath": "data.csv"
564
- }
565
- }
566
- ```
567
- ```json
568
- {
569
- "type": "mongodb",
570
- "options": {
571
- "url": "mongodb://localhost:27017",
572
- "database": "databaseName",
573
- "collection": "collectionName"
574
- }
575
- }
576
- ```
577
-
578
- ```json
579
- {
580
- "type": "mysql",
581
- "options": {
582
- "host": "localhost:port",
583
- "user": "username",
584
- "password": "password",
585
- "database": "databaseName"
586
- }
587
- }
588
- ```
589
-
590
- ```json
591
- {
592
- "type": "sqlite",
593
- "options": {
594
- "filePath": "path/to/sqlite/file.db"
595
- }
596
- }
597
- ```
598
-
599
- ```json
600
- {
601
- "type": "redis",
602
- "options": {
603
- "host": "127.0.0.1",
604
- "port": 6379
605
- }
606
- }
607
- ```
608
-
609
- ```json
610
- {
611
- "type": "postgresql",
612
- "options": {
613
- "host": "localhost",
614
- "user": "username",
615
- "password": "password",
616
- "database": "databaseName",
617
- "port": 5432
618
- }
619
- }
620
- ```