@onurege3467/zerohelper 2.0.2 → 2.1.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/database/index.js CHANGED
@@ -1,11 +1,34 @@
1
+ /**
2
+ * @module Database
3
+ */
4
+
1
5
  var JsonDatabase = require("./jsondatabase/index");
2
6
  var MongoDB = require("./mongodb/index");
3
7
  var MySQLDatabase = require("./mysql/index");
4
8
  var SQLiteDatabase = require("./sqldb/index");
5
9
 
6
10
  module.exports = {
11
+ /**
12
+ * JSON-based database.
13
+ * @type {JsonDatabase}
14
+ */
7
15
  JsonDatabase,
16
+
17
+ /**
18
+ * MongoDB-based database.
19
+ * @type {MongoDB}
20
+ */
8
21
  MongoDB,
22
+
23
+ /**
24
+ * MySQL-based database.
25
+ * @type {MySQLDatabase}
26
+ */
9
27
  MySQLDatabase,
28
+
29
+ /**
30
+ * SQLite-based database.
31
+ * @type {SQLiteDatabase}
32
+ */
10
33
  SQLiteDatabase,
11
34
  };
@@ -1,58 +1,135 @@
1
1
  const fs = require("fs");
2
2
  const path = require("path");
3
3
  const sqlite3 = require("sqlite3").verbose();
4
+
4
5
  class Database {
5
6
  constructor(dbFilePath) {
6
7
  this.dbFilePath = dbFilePath || path.join(__dirname, "database.sqlite");
7
8
  this.db = null;
9
+
10
+ // Veritabanı hazır olana kadar işlemleri bekletmek için bir Promise
11
+ this.ready = new Promise((resolve, reject) => {
12
+ if (!fs.existsSync(this.dbFilePath)) {
13
+ console.log("Database file does not exist. Creating the file...");
14
+ fs.writeFileSync(this.dbFilePath, ""); // Boş bir dosya oluştur
15
+ }
16
+
17
+ // Veritabanını başlat
18
+ this.db = new sqlite3.Database(this.dbFilePath, (err) => {
19
+ if (err) {
20
+ console.error("Error opening database:", err.message);
21
+ reject(err);
22
+ } else {
23
+ console.log("Connected to the SQLite database.");
24
+ this.runQuery(
25
+ `CREATE TABLE IF NOT EXISTS key_value_store (key TEXT PRIMARY KEY, value TEXT)`
26
+ )
27
+ .then(() => {
28
+ console.log("Table initialized");
29
+ resolve(); // Veritabanı hazır
30
+ })
31
+ .catch((err) => {
32
+ console.error(err);
33
+ reject(err);
34
+ });
35
+ }
36
+ });
37
+ });
8
38
  }
9
39
 
10
- initialize() {
11
- if (!fs.existsSync(this.dbFilePath)) {
12
- console.log("Creating database file...");
13
- fs.writeFileSync(this.dbFilePath, "");
40
+ _ensureDatabaseInitialized() {
41
+ if (!this.db) {
42
+ throw new Error(
43
+ "Database is not initialized. Ensure the database file exists."
44
+ );
14
45
  }
46
+ }
47
+
48
+ _parseNestedKey(key) {
49
+ return key.includes(".") ? key.split(".") : [key];
50
+ }
51
+
52
+ _buildNestedObject(keys, value) {
53
+ return keys.reverse().reduce((acc, curr) => ({ [curr]: acc }), value);
54
+ }
15
55
 
16
- this.db = new sqlite3.Database(this.dbFilePath, (err) => {
17
- if (err) {
18
- console.error("Error opening database:", err.message);
19
- } else {
20
- console.log("Connected to the SQLite database.");
21
- this.runQuery(
22
- `CREATE TABLE IF NOT EXISTS key_value_store (key TEXT PRIMARY KEY, value TEXT)`
23
- )
24
- .then(() => {
25
- console.log("Table initialized");
26
- })
27
- .catch((err) => console.error(err));
56
+ _mergeObjects(target, source) {
57
+ for (const key in source) {
58
+ if (source[key] instanceof Object && key in target) {
59
+ Object.assign(
60
+ source[key],
61
+ this._mergeObjects(target[key], source[key])
62
+ );
28
63
  }
29
- });
64
+ }
65
+ return { ...target, ...source };
30
66
  }
31
67
 
32
- set(key, value) {
68
+ async set(key, value) {
69
+ await this.ready; // Veritabanı hazır olana kadar bekle
70
+ this._ensureDatabaseInitialized();
71
+ const keys = this._parseNestedKey(key);
72
+ if (keys.length > 1) {
73
+ return this.get(keys[0]).then((currentValue) => {
74
+ const nestedObject = this._buildNestedObject(keys.slice(1), value);
75
+ const mergedValue = this._mergeObjects(
76
+ currentValue || {},
77
+ nestedObject
78
+ );
79
+ return this.set(keys[0], mergedValue);
80
+ });
81
+ }
82
+
33
83
  return this.runQuery(
34
84
  `INSERT INTO key_value_store (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value`,
35
85
  [key, JSON.stringify(value)]
36
86
  );
37
87
  }
38
88
 
39
- get(key) {
89
+ async get(key) {
90
+ await this.ready; // Veritabanı hazır olana kadar bekle
91
+ this._ensureDatabaseInitialized();
92
+ const keys = this._parseNestedKey(key);
40
93
  return this.getQuery(`SELECT value FROM key_value_store WHERE key = ?`, [
41
- key,
42
- ]).then((row) => (row ? JSON.parse(row.value) : null));
94
+ keys[0],
95
+ ]).then((row) => {
96
+ if (!row) return null;
97
+ const value = JSON.parse(row.value);
98
+ return keys.length > 1
99
+ ? keys.slice(1).reduce((acc, curr) => (acc ? acc[curr] : null), value)
100
+ : value;
101
+ });
43
102
  }
44
103
 
45
- delete(key) {
104
+ async delete(key) {
105
+ await this.ready; // Veritabanı hazır olana kadar bekle
106
+ this._ensureDatabaseInitialized();
107
+ const keys = this._parseNestedKey(key);
108
+ if (keys.length > 1) {
109
+ return this.get(keys[0]).then((currentValue) => {
110
+ if (!currentValue) return null;
111
+ let ref = currentValue;
112
+ for (let i = 0; i < keys.length - 1; i++) {
113
+ if (!ref[keys[i]]) return null;
114
+ if (i === keys.length - 2) {
115
+ delete ref[keys[i + 1]];
116
+ } else {
117
+ ref = ref[keys[i]];
118
+ }
119
+ }
120
+ return this.set(keys[0], currentValue);
121
+ });
122
+ }
46
123
  return this.runQuery(`DELETE FROM key_value_store WHERE key = ?`, [key]);
47
124
  }
48
125
 
49
- has(key) {
50
- return this.getQuery(`SELECT 1 FROM key_value_store WHERE key = ?`, [
51
- key,
52
- ]).then((row) => !!row);
126
+ async has(key) {
127
+ await this.ready; // Veritabanı hazır olana kadar bekle
128
+ return this.get(key).then((value) => value !== null);
53
129
  }
54
130
 
55
- push(key, value) {
131
+ async push(key, value) {
132
+ await this.ready; // Veritabanı hazır olana kadar bekle
56
133
  return this.get(key).then((currentValue) => {
57
134
  if (!Array.isArray(currentValue)) {
58
135
  currentValue = [];
@@ -62,7 +139,8 @@ class Database {
62
139
  });
63
140
  }
64
141
 
65
- add(key, value) {
142
+ async add(key, value) {
143
+ await this.ready; // Veritabanı hazır olana kadar bekle
66
144
  return this.get(key).then((currentValue) => {
67
145
  if (typeof currentValue !== "number") {
68
146
  currentValue = 0;
@@ -71,7 +149,8 @@ class Database {
71
149
  });
72
150
  }
73
151
 
74
- sub(key, value) {
152
+ async sub(key, value) {
153
+ await this.ready; // Veritabanı hazır olana kadar bekle
75
154
  return this.get(key).then((currentValue) => {
76
155
  if (typeof currentValue !== "number") {
77
156
  currentValue = 0;
@@ -105,13 +184,15 @@ class Database {
105
184
  }
106
185
 
107
186
  close() {
108
- this.db.close((err) => {
109
- if (err) {
110
- console.error("Error closing database:", err.message);
111
- } else {
112
- console.log("Database connection closed.");
113
- }
114
- });
187
+ if (this.db) {
188
+ this.db.close((err) => {
189
+ if (err) {
190
+ console.error("Error closing database:", err.message);
191
+ } else {
192
+ console.log("Database connection closed.");
193
+ }
194
+ });
195
+ }
115
196
  }
116
197
  }
117
198
 
@@ -119,23 +200,11 @@ module.exports = Database;
119
200
 
120
201
  // Example usage:
121
202
  // const db = new Database();
122
- // db.initialize();
123
- // db.set('foo', 'bar')
203
+ // db.set('foo.bar.baz', 'value')
204
+ // .then(() => db.get('foo.bar'))
205
+ // .then((value) => console.log('Value:', value)) // Output: { baz: 'value' }
206
+ // .then(() => db.delete('foo.bar.baz'))
124
207
  // .then(() => db.get('foo'))
125
- // .then((value) => console.log('Value:', value)) // Output: bar
126
- // .then(() => db.push('array', 'x'))
127
- // .then(() => db.get('array'))
128
- // .then((value) => console.log('Array:', value)) // Output: ['x']
129
- // .then(() => db.add('number', 1))
130
- // .then(() => db.get('number'))
131
- // .then((value) => console.log('Number:', value)) // Output: 1
132
- // .then(() => db.sub('number', 1))
133
- // .then(() => db.get('number'))
134
- // .then((value) => console.log('Number after sub:', value)) // Output: 0
135
- // .then(() => db.has('foo'))
136
- // .then((exists) => console.log('Exists:', exists)) // Output: true
137
- // .then(() => db.delete('foo'))
138
- // .then(() => db.has('foo'))
139
- // .then((exists) => console.log('Exists after delete:', exists)) // Output: false
208
+ // .then((value) => console.log('After delete:', value)) // Output: {}
140
209
  // .catch((err) => console.error(err))
141
210
  // .finally(() => db.close());
package/database/test.js CHANGED
@@ -43,9 +43,8 @@ const runJsonDatabase = async () => {
43
43
  const runSQLite = async () => {
44
44
  const { database } = require("../index");
45
45
  var db = new database.SQLiteDatabase();
46
- await db.initialize();
47
- await db.set("foo", "bar");
48
- console.log(await db.get("foo"));
46
+ await db.set("foo.test", "bar");
47
+ console.log(await db.get("foo.test"));
49
48
  };
50
49
 
51
50
  runSQLite();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@onurege3467/zerohelper",
3
- "version": "2.0.2",
3
+ "version": "2.1.0",
4
4
  "main": "index.js",
5
5
  "scripts": {
6
6
  "test": "node test.js"