@onurege3467/zerohelper 3.1.0 → 3.2.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
@@ -8,6 +8,7 @@ var MySQLDatabase = require("./mysql/index");
8
8
  var SQLiteDatabase = require("./sqldb/index");
9
9
  var RedisDatabase = require("./redis/index");
10
10
  var PostgreSQL = require("./postgresql/index");
11
+ var MigrateDatabase = require("./migrate/index");
11
12
 
12
13
  module.exports = {
13
14
  /**
@@ -45,4 +46,9 @@ module.exports = {
45
46
  * @type {PostgreSQL}
46
47
  */
47
48
  PostgreSQL,
49
+ /**
50
+ * Migration utility for databases.
51
+ * @type {MigrateDatabase}
52
+ */
53
+ MigrateDatabase,
48
54
  };
@@ -33,6 +33,11 @@ class database {
33
33
  this.set(path, data);
34
34
  return data;
35
35
  }
36
+ getAllData() {
37
+ let data = this.read();
38
+ if (!data) data = {};
39
+ return data;
40
+ }
36
41
  get(path) {
37
42
  let data = this.read(),
38
43
  result = undefined;
@@ -72,9 +77,9 @@ class database {
72
77
  push(path, value) {
73
78
  let data = this.read();
74
79
  if (!data) data = {};
75
- if (_get(path,data) && Array.isArray(_get(path,data))) {
76
- _get(path,data).push(value);
77
- } else if (!_get(path,data)) {
80
+ if (_get(path, data) && Array.isArray(_get(path, data))) {
81
+ _get(path, data).push(value);
82
+ } else if (!_get(path, data)) {
78
83
  _set(path, [value], data);
79
84
  }
80
85
  fs.truncateSync(this.FilePath);
@@ -0,0 +1,63 @@
1
+ const JsonDatabase = require("../jsondatabase/index");
2
+ const MongoDB = require("../mongodb/index");
3
+ const MySQLDatabase = require("../mysql/index");
4
+ const SQLiteDatabase = require("../sqldb/index");
5
+ const RedisDatabase = require("../redis/index");
6
+ const PostgreSQL = require("../postgresql/index");
7
+
8
+ /**
9
+ * Migrates data from one database to another.
10
+ * @param {Object} source - Source database configuration.
11
+ * @param {Object} target - Target database configuration.
12
+ */
13
+ async function migrateData(source, target) {
14
+ const sourceDb = await initializeDatabase(source);
15
+ const targetDb = await initializeDatabase(target);
16
+
17
+ const allData = await sourceDb.getAllData();
18
+ console.log(allData);
19
+
20
+ for (const [key, value] of Object.entries(allData)) {
21
+ await targetDb.set(key, value);
22
+ }
23
+
24
+ console.log(`Migration completed from ${source.type} to ${target.type}`);
25
+ }
26
+
27
+ /**
28
+ * Initializes a database instance based on the configuration.
29
+ * @param {Object} config - Database configuration.
30
+ * @returns {Object} - Database instance.
31
+ */
32
+ async function initializeDatabase(config) {
33
+ switch (config.type) {
34
+ case "json":
35
+ return new JsonDatabase(config.options.filePath);
36
+ case "mongodb":
37
+ const mongoClient = await MongoDB.createData(
38
+ config.options.database,
39
+ config.options.collection,
40
+ config.options.data,
41
+ undefined,
42
+ config.options.url
43
+ );
44
+ return mongoClient;
45
+ case "mysql":
46
+ const mysqlDb = new MySQLDatabase();
47
+ await mysqlDb.connect(config.options);
48
+ return mysqlDb;
49
+ case "sqlite":
50
+ return new SQLiteDatabase(config.options.filePath);
51
+ case "redis":
52
+ const redisDb = new RedisDatabase(config.options);
53
+ await redisDb.connect();
54
+ return redisDb;
55
+ case "postgresql":
56
+ return new PostgreSQL(config.options);
57
+ default:
58
+ throw new Error(`Unsupported database type: ${config.type}`);
59
+ }
60
+ }
61
+
62
+ // Export the migrateData function
63
+ module.exports = migrateData;
@@ -2,227 +2,281 @@ const mongodb = require("mongodb");
2
2
  const PathFormat = require("../tools/FormatTool.js");
3
3
 
4
4
  class Data {
5
- /**
6
- * @type {mongodb.Collection}
7
- */
8
- #collection;
9
- /**
10
- * @type {String}
11
- */
12
- #key;
13
-
14
- /**
15
- *
16
- * @param {String} key
17
- * @param {mongodb.Collection} collection
18
- */
19
- constructor(key, collection) {
20
- this.#key = key;
21
- this.#collection = collection;
22
- }
23
-
24
- /**
25
- * Assign to the specified path.
26
- * @param {String} path
27
- * @param {any} value Value to be assigned.
28
- * @return {any}
29
- */
30
- async set(path, value) {
31
- path = PathFormat(path);
32
-
33
- await this.#collection.updateOne({ key: this.#key }, { $set: { [path]: value } }, { upsert: true });
34
- return value;
35
- }
36
-
37
- /**
38
- * Deletes the specified path.
39
- * @param {String} path
40
- * @return {Promise<void>}
41
- */
42
- async delete(path) {
43
- path = PathFormat(path);
44
-
45
- await this.#collection.updateOne({ key: this.#key }, { $unset: { [path]: "" } });
46
- }
47
-
48
- /**
49
- * Returns the value/object at the specified path.
50
- * @param {String} path
51
- * @return {any}
52
- */
53
- async get(path) {
54
- path = PathFormat(path);
55
-
56
- const data = await this.#collection.findOne({ key: this.#key }, {
57
- projection: {
58
- "result": `$${path}`
59
- }
60
- });
61
-
62
- return data ? data.result : undefined;
63
- }
64
-
65
- async getAll() {
66
-
67
- const data = await this.#collection.findOne({ key: this.#key })
68
-
69
- return data ? data.data : {};
70
- }
71
-
72
- async ping() {
73
- var run1 = Date.now()
74
- await this.set(`${run1}`,1)
75
- var set = Date.now()
76
- var run2 = Date.now()
77
- await this.get(run1)
78
- var get = Date.now()
79
- var run3 = Date.now()
80
- await this.delete(run1)
81
- var deletet = Date.now()
82
-
83
- return {total:((get+set+deletet)/3)-run1,set:set-run1,get:get-run2,delete:deletet-run3}
84
- }
85
-
86
- /**
87
- * Sorts the array/values ​​in path.
88
- * @param {String} path
89
- * @param {("DESC"|"ASC")} orderType Sorts the data in DESC (descending) or ASC (ascending).
90
- * @param {Number} limit determines how many elements will rotate. (Default: 0 this is mean of returns in array all elements)
91
- * @return {Promise<any[]>}
92
- */
93
- async sort(path, orderType, limit = 0) {
94
- path = PathFormat(path);
95
-
96
- const order = orderType == "DESC" ? -1 : 1;
97
- const pipelines = [
98
- {
99
- '$match': {
100
- 'key': this.#key
101
- }
102
- }, {
103
- '$unwind': {
104
- 'path': `$${path}`
105
- }
106
- }, {
107
- '$sort': {
108
- [`${path}`]: order
109
- }
110
- }, {
111
- '$project': {
112
- 'element': `$${path}`
113
- }
114
- }, {
115
- '$limit': limit
116
- }
117
- ];
118
-
119
- let result = (await this.#collection.aggregate(pipelines).toArray()).map(e => e.element);
120
- return result;
121
- }
122
-
123
- /**
124
- * Do mathematical addition to specified path.
125
- * @param {String} path
126
- * @param {Number} value
127
- * @return {any}
128
- */
129
- async add(path, value) {
130
- path = PathFormat(path);
131
-
132
- const data = await this.#collection.findOneAndUpdate({ key: this.#key }, { $inc: { [path]: value } }, {
133
- projection: {
134
- "result": `$${path}`
135
- },
136
- upsert: true,
137
- new: true
138
- });
139
-
140
- return data ? data.result : undefined;
141
- }
142
-
143
- /**
144
- * Do mathematical subtraction to specified path.
145
- * @param {String} path
146
- * @param {Number} value
147
- * @return {any}
148
- */
149
- async sub(path, value) {
150
- path = PathFormat(path);
151
-
152
- const data = await this.#collection.findOneAndUpdate({ key: this.#key }, { $inc: { [path]: -Math.abs(value) } }, {
153
- projection: {
154
- "result": `$${path}`
155
- },
156
- upsert: true,
157
- new: true
158
- });
159
-
160
- return data ? data.result : undefined;
161
- }
162
-
163
- /**
164
- * Check if Field exists to specified path.
165
- * @param {String} path
166
- * @return {Promise<Boolean>}
167
- */
168
- async has(path) {
169
- path = PathFormat(path);
170
-
171
- const data = await this.#collection.findOne({ key: this.#key, [path]: { $exists: true } }, {
172
- projection: {
173
- "_id": 1
174
- }
175
- });
176
- return data ? true : false;
177
- }
178
-
179
- /**
180
- * Push to value an array to specified path.
181
- * @param {String} path
182
- * @param {any} value
183
- * @return {Promise<void>}
184
- */
185
- async push(path, value) {
186
- path = PathFormat(path);
187
-
188
- await this.#collection.updateOne({ key: this.#key }, { $push: { [path]: value } }, { upsert: true });
189
- }
190
-
191
- /**
192
- * Push to multiple values an array to specified path.
193
- * @param {String} path
194
- * @param {any[]} values
195
- * @return {Promise<void>}
196
- */
197
- async pushRange(path, values) {
198
- path = PathFormat(path);
199
-
200
- await this.#collection.updateOne({ key: this.#key }, { $push: { [path]: { $each: values } } }, { upsert: true });
201
- }
202
-
203
- /**
204
- * Extract element from Array to specified path.
205
- * @param {String} path
206
- * @param {any} value
207
- * @return {Promise<void>}
208
- */
209
- async pull(path, value) {
210
- path = PathFormat(path);
211
-
212
- await this.#collection.updateOne({ key: this.#key }, { $pull: { [path]: value } }, { upsert: true });
213
- }
214
-
215
- /**
216
- * Extract all elements from Array to specified path.
217
- * @param {String} path
218
- * @param {any} value
219
- * @return {Promise<void>}
220
- */
221
- async pullAll(path, value) {
222
- path = PathFormat(path);
223
-
224
- await this.#collection.updateOne({ key: this.#key }, { $pullAll: { [path]: value } }, { upsert: true });
225
- }
5
+ /**
6
+ * @type {mongodb.Collection}
7
+ */
8
+ #collection;
9
+ /**
10
+ * @type {String}
11
+ */
12
+ #key;
13
+
14
+ /**
15
+ *
16
+ * @param {String} key
17
+ * @param {mongodb.Collection} collection
18
+ */
19
+ constructor(key, collection) {
20
+ this.#key = key;
21
+ this.#collection = collection;
22
+ }
23
+
24
+ /**
25
+ * Assign to the specified path.
26
+ * @param {String} path
27
+ * @param {any} value Value to be assigned.
28
+ * @return {any}
29
+ */
30
+ async set(path, value) {
31
+ path = PathFormat(path);
32
+
33
+ await this.#collection.updateOne(
34
+ { key: this.#key },
35
+ { $set: { [path]: value } },
36
+ { upsert: true }
37
+ );
38
+ return value;
39
+ }
40
+
41
+ /**
42
+ * Deletes the specified path.
43
+ * @param {String} path
44
+ * @return {Promise<void>}
45
+ */
46
+ async delete(path) {
47
+ path = PathFormat(path);
48
+
49
+ await this.#collection.updateOne(
50
+ { key: this.#key },
51
+ { $unset: { [path]: "" } }
52
+ );
53
+ }
54
+
55
+ /**
56
+ * Returns the value/object at the specified path.
57
+ * @param {String} path
58
+ * @return {any}
59
+ */
60
+ async get(path) {
61
+ path = PathFormat(path);
62
+
63
+ const data = await this.#collection.findOne(
64
+ { key: this.#key },
65
+ {
66
+ projection: {
67
+ result: `$${path}`,
68
+ },
69
+ }
70
+ );
71
+
72
+ return data ? data.result : undefined;
73
+ }
74
+
75
+ async getAll() {
76
+ const data = await this.#collection.findOne({ key: this.#key });
77
+
78
+ return data ? data.data : {};
79
+ }
80
+
81
+ async getAllData() {
82
+ this.getAll().then((data) => {
83
+ if (!data) data = {};
84
+ return data;
85
+ });
86
+ }
87
+
88
+ async ping() {
89
+ var run1 = Date.now();
90
+ await this.set(`${run1}`, 1);
91
+ var set = Date.now();
92
+ var run2 = Date.now();
93
+ await this.get(run1);
94
+ var get = Date.now();
95
+ var run3 = Date.now();
96
+ await this.delete(run1);
97
+ var deletet = Date.now();
98
+
99
+ return {
100
+ total: (get + set + deletet) / 3 - run1,
101
+ set: set - run1,
102
+ get: get - run2,
103
+ delete: deletet - run3,
104
+ };
105
+ }
106
+
107
+ /**
108
+ * Sorts the array/values ​​in path.
109
+ * @param {String} path
110
+ * @param {("DESC"|"ASC")} orderType Sorts the data in DESC (descending) or ASC (ascending).
111
+ * @param {Number} limit determines how many elements will rotate. (Default: 0 this is mean of returns in array all elements)
112
+ * @return {Promise<any[]>}
113
+ */
114
+ async sort(path, orderType, limit = 0) {
115
+ path = PathFormat(path);
116
+
117
+ const order = orderType == "DESC" ? -1 : 1;
118
+ const pipelines = [
119
+ {
120
+ $match: {
121
+ key: this.#key,
122
+ },
123
+ },
124
+ {
125
+ $unwind: {
126
+ path: `$${path}`,
127
+ },
128
+ },
129
+ {
130
+ $sort: {
131
+ [`${path}`]: order,
132
+ },
133
+ },
134
+ {
135
+ $project: {
136
+ element: `$${path}`,
137
+ },
138
+ },
139
+ {
140
+ $limit: limit,
141
+ },
142
+ ];
143
+
144
+ let result = (await this.#collection.aggregate(pipelines).toArray()).map(
145
+ (e) => e.element
146
+ );
147
+ return result;
148
+ }
149
+
150
+ /**
151
+ * Do mathematical addition to specified path.
152
+ * @param {String} path
153
+ * @param {Number} value
154
+ * @return {any}
155
+ */
156
+ async add(path, value) {
157
+ path = PathFormat(path);
158
+
159
+ const data = await this.#collection.findOneAndUpdate(
160
+ { key: this.#key },
161
+ { $inc: { [path]: value } },
162
+ {
163
+ projection: {
164
+ result: `$${path}`,
165
+ },
166
+ upsert: true,
167
+ new: true,
168
+ }
169
+ );
170
+
171
+ return data ? data.result : undefined;
172
+ }
173
+
174
+ /**
175
+ * Do mathematical subtraction to specified path.
176
+ * @param {String} path
177
+ * @param {Number} value
178
+ * @return {any}
179
+ */
180
+ async sub(path, value) {
181
+ path = PathFormat(path);
182
+
183
+ const data = await this.#collection.findOneAndUpdate(
184
+ { key: this.#key },
185
+ { $inc: { [path]: -Math.abs(value) } },
186
+ {
187
+ projection: {
188
+ result: `$${path}`,
189
+ },
190
+ upsert: true,
191
+ new: true,
192
+ }
193
+ );
194
+
195
+ return data ? data.result : undefined;
196
+ }
197
+
198
+ /**
199
+ * Check if Field exists to specified path.
200
+ * @param {String} path
201
+ * @return {Promise<Boolean>}
202
+ */
203
+ async has(path) {
204
+ path = PathFormat(path);
205
+
206
+ const data = await this.#collection.findOne(
207
+ { key: this.#key, [path]: { $exists: true } },
208
+ {
209
+ projection: {
210
+ _id: 1,
211
+ },
212
+ }
213
+ );
214
+ return data ? true : false;
215
+ }
216
+
217
+ /**
218
+ * Push to value an array to specified path.
219
+ * @param {String} path
220
+ * @param {any} value
221
+ * @return {Promise<void>}
222
+ */
223
+ async push(path, value) {
224
+ path = PathFormat(path);
225
+
226
+ await this.#collection.updateOne(
227
+ { key: this.#key },
228
+ { $push: { [path]: value } },
229
+ { upsert: true }
230
+ );
231
+ }
232
+
233
+ /**
234
+ * Push to multiple values an array to specified path.
235
+ * @param {String} path
236
+ * @param {any[]} values
237
+ * @return {Promise<void>}
238
+ */
239
+ async pushRange(path, values) {
240
+ path = PathFormat(path);
241
+
242
+ await this.#collection.updateOne(
243
+ { key: this.#key },
244
+ { $push: { [path]: { $each: values } } },
245
+ { upsert: true }
246
+ );
247
+ }
248
+
249
+ /**
250
+ * Extract element from Array to specified path.
251
+ * @param {String} path
252
+ * @param {any} value
253
+ * @return {Promise<void>}
254
+ */
255
+ async pull(path, value) {
256
+ path = PathFormat(path);
257
+
258
+ await this.#collection.updateOne(
259
+ { key: this.#key },
260
+ { $pull: { [path]: value } },
261
+ { upsert: true }
262
+ );
263
+ }
264
+
265
+ /**
266
+ * Extract all elements from Array to specified path.
267
+ * @param {String} path
268
+ * @param {any} value
269
+ * @return {Promise<void>}
270
+ */
271
+ async pullAll(path, value) {
272
+ path = PathFormat(path);
273
+
274
+ await this.#collection.updateOne(
275
+ { key: this.#key },
276
+ { $pullAll: { [path]: value } },
277
+ { upsert: true }
278
+ );
279
+ }
226
280
  }
227
281
 
228
282
  module.exports = { Data };
@@ -1,37 +1,41 @@
1
1
  "use strict";
2
2
 
3
- const EventEmitter = require('events');
3
+ const EventEmitter = require("events");
4
+ const getAllData = require("../methods/getAllData");
4
5
 
5
- module.exports = class MySQL extends EventEmitter{
6
- constructor(){ super() };
7
- name = 'FxesDbMySQL';
8
- version = '1.0.0';
9
- connect = require('../methods/connect');
10
- query = require('../methods/query');
11
- get = require('../methods/get');
12
- set = require('../methods/set');
13
- push = require('../methods/push');
14
- includes = require('../methods/includes');
15
- pull = require('../methods/pull');
16
- add = require('../methods/add');
17
- sub = require('../methods/sub');
18
- subtract = require('../methods/sub');
19
- delete = require('../methods/delete');
20
- all = require('../methods/all');
21
- tables = require('../methods/tables');
22
- rename = require('../methods/rename');
23
- stats = require('../methods/stats');
24
- auto_increment = require('../methods/auto_increment');
25
- create = require('../methods/create');
26
- drop = require('../methods/drop');
27
- variables = require('../methods/variables');
28
- process = require('../methods/process');
29
- ping = require('../methods/ping');
30
- clear = require('../methods/clear');
31
- base_set = require('../methods/base_set');
32
- base_get = require('../methods/base_get');
33
- end = require('../methods/end');
34
- exists = require('../methods/exists');
35
- create_db = require('../methods/create_db');
36
- has = require('../methods/has')
37
- }
6
+ module.exports = class MySQL extends EventEmitter {
7
+ constructor() {
8
+ super();
9
+ }
10
+ name = "FxesDbMySQL";
11
+ version = "1.0.0";
12
+ connect = require("../methods/connect");
13
+ getAllData = getAllData;
14
+ query = require("../methods/query");
15
+ get = require("../methods/get");
16
+ set = require("../methods/set");
17
+ push = require("../methods/push");
18
+ includes = require("../methods/includes");
19
+ pull = require("../methods/pull");
20
+ add = require("../methods/add");
21
+ sub = require("../methods/sub");
22
+ subtract = require("../methods/sub");
23
+ delete = require("../methods/delete");
24
+ all = require("../methods/all");
25
+ tables = require("../methods/tables");
26
+ rename = require("../methods/rename");
27
+ stats = require("../methods/stats");
28
+ auto_increment = require("../methods/auto_increment");
29
+ create = require("../methods/create");
30
+ drop = require("../methods/drop");
31
+ variables = require("../methods/variables");
32
+ process = require("../methods/process");
33
+ ping = require("../methods/ping");
34
+ clear = require("../methods/clear");
35
+ base_set = require("../methods/base_set");
36
+ base_get = require("../methods/base_get");
37
+ end = require("../methods/end");
38
+ exists = require("../methods/exists");
39
+ create_db = require("../methods/create_db");
40
+ has = require("../methods/has");
41
+ };
@@ -0,0 +1,35 @@
1
+ "use strict";
2
+
3
+ const errors = require("../errors/strings.js");
4
+
5
+ module.exports = async function (table = "default") {
6
+ if (!table || typeof table !== "string") {
7
+ throw new TypeError(errors.table.replace("{received}", typeof table));
8
+ }
9
+
10
+ // Tabloları kontrol et
11
+ let tables = await this.tables();
12
+ if (!tables.includes(table)) {
13
+ throw new TypeError(errors.tableNotFound.replace("{table}", table));
14
+ }
15
+
16
+ // Tüm verileri al
17
+ let all = await this.query(`SELECT key_name, value FROM \`${table}\``);
18
+ let result = {};
19
+
20
+ all.forEach((row) => {
21
+ let key = row.key_name;
22
+ let value = row.value;
23
+
24
+ // JSON parse işlemi
25
+ try {
26
+ value = JSON.parse(value);
27
+ } catch (e) {
28
+ // JSON değilse olduğu gibi bırak
29
+ }
30
+
31
+ result[key] = value;
32
+ });
33
+
34
+ return result;
35
+ };
@@ -3,6 +3,25 @@ const { Pool } = require("pg");
3
3
  class PostgreSQL {
4
4
  constructor(config) {
5
5
  this.pool = new Pool(config);
6
+
7
+ // Ensure the table exists when the class is instantiated
8
+ this.ensureTableExists(config).catch((error) => {
9
+ console.error("Error ensuring table exists:", error);
10
+ });
11
+ }
12
+
13
+ async ensureTableExists(config) {
14
+ try {
15
+ await this.pool.query(`
16
+ CREATE TABLE IF NOT EXISTS key_value_store (
17
+ key TEXT PRIMARY KEY,
18
+ value TEXT NOT NULL
19
+ )
20
+ `);
21
+ } catch (error) {
22
+ console.error("Failed to create table:", error);
23
+ throw error;
24
+ }
6
25
  }
7
26
 
8
27
  async set(key, value) {
@@ -88,7 +107,32 @@ class PostgreSQL {
88
107
  currentValue.push(value);
89
108
  await this.set(key, currentValue);
90
109
  }
91
-
110
+ async getAllData() {
111
+ try {
112
+ const res = await this.pool.query(
113
+ "SELECT key, value FROM key_value_store"
114
+ );
115
+ const result = {};
116
+
117
+ res.rows.forEach((row) => {
118
+ let value = row.value;
119
+
120
+ // JSON parse işlemi
121
+ try {
122
+ value = JSON.parse(value);
123
+ } catch (e) {
124
+ // JSON değilse olduğu gibi bırak
125
+ }
126
+
127
+ result[row.key] = value;
128
+ });
129
+
130
+ return result;
131
+ } catch (error) {
132
+ console.error("Error fetching all data:", error);
133
+ throw error;
134
+ }
135
+ }
92
136
  async ping() {
93
137
  try {
94
138
  await this.pool.query("SELECT 1");
@@ -103,16 +147,4 @@ class PostgreSQL {
103
147
  }
104
148
  }
105
149
 
106
- // Ensure the table exists
107
- (async () => {
108
- const pool = new Pool();
109
- await pool.query(`
110
- CREATE TABLE IF NOT EXISTS key_value_store (
111
- key TEXT PRIMARY KEY,
112
- value TEXT NOT NULL
113
- )
114
- `);
115
- await pool.end();
116
- })();
117
-
118
150
  module.exports = PostgreSQL;
@@ -84,7 +84,30 @@ class RedisDatabase {
84
84
  currentValue.push(value);
85
85
  await this.set(key, currentValue);
86
86
  }
87
-
87
+ async getAllData() {
88
+ try {
89
+ const keys = await this.client.keys("*"); // Tüm anahtarları al
90
+ const result = {};
91
+
92
+ for (const key of keys) {
93
+ let value = await this.client.get(key);
94
+
95
+ // JSON parse işlemi
96
+ try {
97
+ value = JSON.parse(value);
98
+ } catch (e) {
99
+ // JSON değilse olduğu gibi bırak
100
+ }
101
+
102
+ result[key] = value;
103
+ }
104
+
105
+ return result;
106
+ } catch (error) {
107
+ console.error("Error fetching all data:", error);
108
+ throw error;
109
+ }
110
+ }
88
111
  async ping() {
89
112
  try {
90
113
  const pong = await this.client.ping();
@@ -187,7 +187,35 @@ class Database {
187
187
  });
188
188
  });
189
189
  }
190
+ async getAllData() {
191
+ await this.ready; // Veritabanı hazır olana kadar bekle
192
+ this._ensureDatabaseInitialized();
193
+
194
+ return new Promise((resolve, reject) => {
195
+ this.db.all(`SELECT key, value FROM key_value_store`, [], (err, rows) => {
196
+ if (err) {
197
+ console.error("Error fetching all data:", err.message);
198
+ return reject(err);
199
+ }
200
+
201
+ const result = {};
202
+ rows.forEach((row) => {
203
+ let value = row.value;
190
204
 
205
+ // JSON parse işlemi
206
+ try {
207
+ value = JSON.parse(value);
208
+ } catch (e) {
209
+ // JSON değilse olduğu gibi bırak
210
+ }
211
+
212
+ result[row.key] = value;
213
+ });
214
+
215
+ resolve(result);
216
+ });
217
+ });
218
+ }
191
219
  close() {
192
220
  if (this.db) {
193
221
  this.db.close((err) => {
@@ -234,9 +234,146 @@ function isPrime(num) {
234
234
  }
235
235
  return true;
236
236
  }
237
+ // Tarih ve Saat İşlemleri
238
+ function formatDate(date, format = "YYYY-MM-DD") {
239
+ const options = {
240
+ year: "numeric",
241
+ month: "2-digit",
242
+ day: "2-digit",
243
+ hour: "2-digit",
244
+ minute: "2-digit",
245
+ second: "2-digit",
246
+ };
247
+ const formattedDate = new Intl.DateTimeFormat("en-US", options).format(date);
248
+ const [month, day, year, hour, minute, second] = formattedDate.match(/\d+/g);
249
+
250
+ return format
251
+ .replace("YYYY", year)
252
+ .replace("MM", month)
253
+ .replace("DD", day)
254
+ .replace("HH", hour)
255
+ .replace("mm", minute)
256
+ .replace("ss", second);
257
+ }
258
+
259
+ function dateDifference(date1, date2) {
260
+ const diffTime = Math.abs(date2 - date1);
261
+ return Math.ceil(diffTime / (1000 * 60 * 60 * 24)); // Gün cinsinden fark
262
+ }
263
+
264
+ function addDays(date, days) {
265
+ const result = new Date(date);
266
+ result.setDate(result.getDate() + days);
267
+ return result;
268
+ }
269
+
270
+ function subtractDays(date, days) {
271
+ const result = new Date(date);
272
+ result.setDate(result.getDate() - days);
273
+ return result;
274
+ }
275
+
276
+ function combination(n, r) {
277
+ return factorial(n) / (factorial(r) * factorial(n - r));
278
+ }
279
+
280
+ function permutation(n, r) {
281
+ return factorial(n) / factorial(n - r);
282
+ }
283
+ const https = require("https");
284
+ const http = require("http");
285
+
286
+ function fetchData(url) {
287
+ return new Promise((resolve, reject) => {
288
+ const client = url.startsWith("https") ? https : http;
289
+
290
+ client
291
+ .get(url, (response) => {
292
+ let data = "";
293
+
294
+ // Gelen veriyi parça parça topluyoruz
295
+ response.on("data", (chunk) => {
296
+ data += chunk;
297
+ });
298
+
299
+ // Veri tamamen alındığında çözümleme yapıyoruz
300
+ response.on("end", () => {
301
+ try {
302
+ resolve(JSON.parse(data));
303
+ } catch (error) {
304
+ resolve(data); // JSON değilse düz metin döndür
305
+ }
306
+ });
307
+ })
308
+ .on("error", (error) => {
309
+ reject(error);
310
+ });
311
+ });
312
+ }
313
+
314
+ function postData(url, data) {
315
+ return new Promise((resolve, reject) => {
316
+ const client = url.startsWith("https") ? https : http;
317
+ const parsedUrl = new URL(url);
318
+
319
+ const options = {
320
+ hostname: parsedUrl.hostname,
321
+ port: parsedUrl.port || (url.startsWith("https") ? 443 : 80),
322
+ path: parsedUrl.pathname,
323
+ method: "POST",
324
+ headers: {
325
+ "Content-Type": "application/json",
326
+ "Content-Length": Buffer.byteLength(JSON.stringify(data)),
327
+ },
328
+ };
329
+
330
+ const req = client.request(options, (response) => {
331
+ let responseData = "";
332
+
333
+ response.on("data", (chunk) => {
334
+ responseData += chunk;
335
+ });
336
+
337
+ response.on("end", () => {
338
+ try {
339
+ resolve(JSON.parse(responseData));
340
+ } catch (error) {
341
+ resolve(responseData); // JSON değilse düz metin döndür
342
+ }
343
+ });
344
+ });
345
+
346
+ req.on("error", (error) => {
347
+ reject(error);
348
+ });
349
+
350
+ // Gönderilecek veriyi yazıyoruz
351
+ req.write(JSON.stringify(data));
352
+ req.end();
353
+ });
354
+ }
237
355
 
356
+ function generateSlug(text) {
357
+ return text
358
+ .toLowerCase()
359
+ .replace(/[^a-z0-9]+/g, "-")
360
+ .replace(/^-+|-+$/g, "");
361
+ }
362
+ function wordCount(text) {
363
+ return text.trim().split(/\s+/).length;
364
+ }
238
365
  // Exportlar
239
366
  module.exports = {
367
+ http: {
368
+ fetchData,
369
+ postData,
370
+ },
371
+ date: {
372
+ formatDate,
373
+ dateDifference,
374
+ addDays,
375
+ subtractDays,
376
+ },
240
377
  random: {
241
378
  makeUniqueId,
242
379
  randomArray,
@@ -249,6 +386,8 @@ module.exports = {
249
386
  string: {
250
387
  titleCase,
251
388
  generateRandomString,
389
+ generateSlug,
390
+ wordCount,
252
391
  },
253
392
  array: {
254
393
  shuffleArray,
@@ -283,5 +422,7 @@ module.exports = {
283
422
  min,
284
423
  range,
285
424
  isPrime,
425
+ combination,
426
+ permutation,
286
427
  },
287
428
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@onurege3467/zerohelper",
3
- "version": "3.1.0",
3
+ "version": "3.2.0",
4
4
  "main": "index.js",
5
5
  "scripts": {
6
6
  "test": "node test.js"
@@ -27,6 +27,7 @@
27
27
  "dependencies": {
28
28
  "bcrypt": "^5.1.1",
29
29
  "crypto": "^1.0.1",
30
+ "dotenv": "^16.4.7",
30
31
  "fs": "^0.0.1-security",
31
32
  "jsonwebtoken": "^9.0.2",
32
33
  "lodash": "^4.17.21",
@@ -37,4 +38,4 @@
37
38
  "redis": "^4.7.0",
38
39
  "sqlite3": "^5.1.7"
39
40
  }
40
- }
41
+ }
package/readme.md CHANGED
@@ -363,3 +363,104 @@ ZeroHelper provides multiple database utilities for seamless integration with va
363
363
  await db.close();
364
364
  })();
365
365
  ```
366
+
367
+ ## Database Migration
368
+
369
+ The `migrateData` function allows you to migrate data between different types of databases. It supports JSON, MongoDB, MySQL, SQLite, Redis, and PostgreSQL.
370
+
371
+ # Example: Migrate Data from JSON to MongoDB
372
+
373
+ ```js
374
+ const migrateData = require("@onurege3467/zerohelper/database/migrate");
375
+
376
+ const sourceConfig = {
377
+ type: "json",
378
+ options: {
379
+ filePath: "databases/source.json", // Path to the JSON file
380
+ },
381
+ };
382
+
383
+ const targetConfig = {
384
+ type: "mongodb",
385
+ options: {
386
+ url: "mongodb://localhost:27017", // MongoDB connection URL
387
+ database: "targetDatabase", // Target database name
388
+ collection: "targetCollection", // Target collection name
389
+ },
390
+ };
391
+
392
+ (async () => {
393
+ try {
394
+ await migrateData(sourceConfig, targetConfig);
395
+ console.log("Data migration completed successfully!");
396
+ } catch (error) {
397
+ console.error("Error during migration:", error);
398
+ }
399
+ })();
400
+ ```
401
+
402
+ # Supported Database Types and Options
403
+
404
+ ```json
405
+ {
406
+ "type": "json",
407
+ "options": {
408
+ "filePath": "path/to/json/file.json"
409
+ }
410
+ }
411
+ ```
412
+
413
+ ```json
414
+ {
415
+ "type": "mongodb",
416
+ "options": {
417
+ "url": "mongodb://localhost:27017",
418
+ "database": "databaseName",
419
+ "collection": "collectionName"
420
+ }
421
+ }
422
+ ```
423
+
424
+ ```json
425
+ {
426
+ "type": "mysql",
427
+ "options": {
428
+ "host": "localhost:port",
429
+ "user": "username",
430
+ "password": "password",
431
+ "database": "databaseName"
432
+ }
433
+ }
434
+ ```
435
+
436
+ ```json
437
+ {
438
+ "type": "sqlite",
439
+ "options": {
440
+ "filePath": "path/to/sqlite/file.db"
441
+ }
442
+ }
443
+ ```
444
+
445
+ ```json
446
+ {
447
+ "type": "redis",
448
+ "options": {
449
+ "host": "127.0.0.1",
450
+ "port": 6379
451
+ }
452
+ }
453
+ ```
454
+
455
+ ```json
456
+ {
457
+ "type": "postgresql",
458
+ "options": {
459
+ "host": "localhost",
460
+ "user": "username",
461
+ "password": "password",
462
+ "database": "databaseName",
463
+ "port": 5432
464
+ }
465
+ }
466
+ ```