@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/test.js CHANGED
@@ -0,0 +1,244 @@
1
+ const path = require('path');
2
+ const createDatabase = require('./database');
3
+ const helpers = require('./functions');
4
+
5
+ const mysqlConfig = {
6
+ adapter: 'mysql',
7
+ config: {
8
+ host: process.env.MYSQL_HOST || 'localhost',
9
+ user: process.env.MYSQL_USER || 'root',
10
+ password: process.env.MYSQL_PASSWORD || '',
11
+ database: process.env.MYSQL_DATABASE || 'test_db_zerohelper',
12
+ cache: {
13
+ max: 100,
14
+ ttl: 1000 * 10,
15
+ updateAgeOnGet: true,
16
+ },
17
+ },
18
+ };
19
+
20
+ const mongoConfig = {
21
+ adapter: 'mongodb',
22
+ config: {
23
+ url: process.env.MONGODB_URL || 'mongodb://localhost:27017/test',
24
+ database: process.env.MONGODB_DATABASE || 'test_mongo_db_zerohelper',
25
+ cache: {
26
+ max: 100,
27
+ ttl: 1000 * 10,
28
+ updateAgeOnGet: true,
29
+ },
30
+ },
31
+ };
32
+
33
+ const jsonConfig = {
34
+ adapter: 'json',
35
+ config: {
36
+ filePath: path.join(__dirname, 'data', 'test_db.json'),
37
+ },
38
+ };
39
+
40
+ const sqliteConfig = {
41
+ adapter: 'sqlite',
42
+ config: {
43
+ filePath: path.join(__dirname, 'data', 'test_db.sqlite'),
44
+ },
45
+ };
46
+
47
+ const cachedSqliteConfig = {
48
+ adapter: 'sqlite',
49
+ config: {
50
+ filePath: path.join(__dirname, 'data', 'test_db_cached.sqlite'),
51
+ cache: {
52
+ max: 100, // Max 100 items
53
+ ttl: 1000 * 10, // 10 seconds TTL
54
+ updateAgeOnGet: true,
55
+ },
56
+ },
57
+ };
58
+
59
+ async function runDatabaseTests() {
60
+ console.log('Starting database tests...');
61
+
62
+ const databases = [
63
+ { name: 'MySQL', config: mysqlConfig },
64
+ { name: 'MongoDB', config: mongoConfig },
65
+ { name: 'JSON', config: jsonConfig },
66
+ { name: 'SQLite', config: sqliteConfig },
67
+ ];
68
+
69
+ for (const dbInfo of databases) {
70
+ const { name, config } = dbInfo;
71
+ console.log(`\n--- Testing ${name} Database ---`);
72
+ let db;
73
+ try {
74
+ db = createDatabase(config);
75
+ console.log(`${name} database connected.`);
76
+
77
+ // Test Insert
78
+ const insertResult = await db.insert('users', { name: 'Test User', email: `test_${name.toLowerCase()}@example.com`, age: 30 });
79
+ console.log(`${name} Insert:`, insertResult);
80
+
81
+ // Test SelectOne
82
+ const user = await db.selectOne('users', { name: 'Test User' });
83
+ console.log(`${name} SelectOne:`, user);
84
+
85
+ // Test Update
86
+ if (user) {
87
+ const updateResult = await db.update('users', { age: 31 }, { name: 'Test User' });
88
+ console.log(`${name} Update:`, updateResult);
89
+ }
90
+
91
+ // Test Select (all)
92
+ const allUsers = await db.select('users');
93
+ console.log(`${name} Select All:`, allUsers);
94
+
95
+ // Test Set (upsert)
96
+ const setResult = await db.set('users', { city: 'Test City' }, { name: 'Test User' });
97
+ console.log(`${name} Set (upsert):`, setResult);
98
+
99
+ // Test Delete
100
+ const deleteResult = await db.delete('users', { name: 'Test User' });
101
+ console.log(`${name} Delete:`, deleteResult);
102
+
103
+ } catch (error) {
104
+ console.error(`Error testing ${name} database:`, error);
105
+ } finally {
106
+ if (db) {
107
+ try {
108
+ await db.close();
109
+ console.log(`${name} database connection closed.`);
110
+ } catch (closeError) {
111
+ console.error(`Error closing ${name} database connection:`, closeError);
112
+ }
113
+ }
114
+ }
115
+ }
116
+
117
+ // --- Testing Cached SQLite Database ---
118
+ console.log('\n--- Testing Cached SQLite Database ---');
119
+ let cachedDb;
120
+ try {
121
+ cachedDb = createDatabase(cachedSqliteConfig);
122
+ console.log('Cached SQLite database connected.');
123
+
124
+ // Insert a record
125
+ await cachedDb.insert('products', { name: 'Laptop', price: 1200 });
126
+ console.log('Inserted Laptop into cached DB.');
127
+
128
+ // First select - should be a cache miss
129
+ let product = await cachedDb.selectOne('products', { name: 'Laptop' });
130
+ console.log('First select (should be cache miss): ', product);
131
+
132
+ // Second select - should be a cache hit
133
+ product = await cachedDb.selectOne('products', { name: 'Laptop' });
134
+ console.log('Second select (should be cache hit): ', product);
135
+
136
+ // Update the record - should invalidate cache
137
+ await cachedDb.update('products', { price: 1150 }, { name: 'Laptop' });
138
+ console.log('Updated Laptop price, cache should be invalidated.');
139
+
140
+ // Third select - should be a cache miss again (after invalidation)
141
+ product = await cachedDb.selectOne('products', { name: 'Laptop' });
142
+ console.log('Third select (should be cache miss after update): ', product);
143
+
144
+ // Delete the record
145
+ await cachedDb.delete('products', { name: 'Laptop' });
146
+ console.log('Deleted Laptop from cached DB.');
147
+
148
+ } catch (error) {
149
+ console.error('Error testing Cached SQLite database:', error);
150
+ } finally {
151
+ if (cachedDb) {
152
+ try {
153
+ await cachedDb.close();
154
+ console.log('Cached SQLite database connection closed.');
155
+ } catch (closeError) {
156
+ console.error('Error closing Cached SQLite database connection:', closeError);
157
+ }
158
+ }
159
+ }
160
+
161
+ console.log('\nAll database tests completed.');
162
+ }
163
+
164
+ function runHelperFunctionTests() {
165
+ console.log('\nStarting helper function tests...');
166
+
167
+ // Random Functions
168
+ console.log('\n--- Testing Random Functions ---');
169
+ console.log('makeUniqueId:', helpers.random.makeUniqueId());
170
+ console.log('randomArray:', helpers.random.randomArray([1, 2, 3]));
171
+ console.log('randomText (5 chars):', helpers.random.randomText(5));
172
+ console.log('randomNumber (1-10):', helpers.random.randomNumber(1, 10));
173
+ console.log('randomEmoji:', helpers.random.randomEmoji());
174
+ console.log('randomHex:', helpers.random.randomHex());
175
+ console.log('randomFloat (1.0-2.0):', helpers.random.randomFloat(1.0, 2.0));
176
+
177
+ // String Functions
178
+ console.log('\n--- Testing String Functions ---');
179
+ console.log('titleCase:', helpers.string.titleCase('hello world'));
180
+ console.log('generateRandomString (8 chars):', helpers.string.generateRandomString(8));
181
+
182
+ // Array Functions
183
+ console.log('\n--- Testing Array Functions ---');
184
+ console.log('shuffleArray:', helpers.array.shuffleArray([1, 2, 3, 4, 5]));
185
+ console.log('flattenArray:', helpers.array.flattenArray([1, [2, [3]], 4]));
186
+ console.log('removeFalsyValues:', helpers.array.removeFalsyValues([0, 1, false, '', null, undefined, 2]));
187
+ const groupByData = [
188
+ { type: 'A', value: 1 },
189
+ { type: 'B', value: 2 },
190
+ { type: 'A', value: 3 },
191
+ ];
192
+ console.log('groupBy:', helpers.array.groupBy(groupByData, 'type'));
193
+ const pluckData = [
194
+ { name: 'Alice', age: 30 },
195
+ { name: 'Bob', age: 24 },
196
+ ];
197
+ console.log('pluck (name):', helpers.array.pluck(pluckData, 'name'));
198
+ const sortByData = [
199
+ { age: 30 },
200
+ { age: 20 },
201
+ { age: 40 },
202
+ ];
203
+ console.log('sortBy (age):', helpers.array.sortBy(sortByData, 'age'));
204
+
205
+ // Object Functions
206
+ console.log('\n--- Testing Object Functions ---');
207
+ const filterObjectData = { a: 1, b: 2, c: 3 };
208
+ console.log('filterObjectByKey:', helpers.object.filterObjectByKey(filterObjectData, ['a', 'c']));
209
+ const deepMergeData1 = { a: 1, b: { c: 2 } };
210
+ const deepMergeData2 = { b: { d: 3 }, e: 4 };
211
+ console.log('deepMerge:', helpers.object.deepMerge(deepMergeData1, deepMergeData2));
212
+
213
+ // Crypto Functions
214
+ console.log('\n--- Testing Crypto Functions ---');
215
+ const secret = 'mySuperSecretKey';
216
+ const textToEncrypt = 'Hello Crypto!';
217
+ const encryptedResult = helpers.crypto.encryptText(textToEncrypt, secret);
218
+ const encryptedText = encryptedResult.encryptedText;
219
+ const iv = encryptedResult.iv;
220
+ console.log('encryptText:', encryptedText);
221
+ console.log('decryptText:', helpers.crypto.decryptText(encryptedText, secret, iv));
222
+ const password = 'mySecurePassword';
223
+ const hashedPassword = helpers.crypto.hashPassword(password);
224
+ console.log('hashPassword:', hashedPassword);
225
+ console.log('verifyPassword (true):', helpers.crypto.verifyPassword(password, hashedPassword));
226
+ console.log('verifyPassword (false):', helpers.crypto.verifyPassword('wrongPassword', hashedPassword));
227
+ const jwtPayload = { userId: 123, username: 'testuser' };
228
+ const jwtToken = helpers.crypto.generateJWT(jwtPayload, secret);
229
+ console.log('generateJWT:', jwtToken);
230
+ console.log('verifyJWT:', helpers.crypto.verifyJWT(jwtToken, secret));
231
+
232
+ // Math Functions
233
+ console.log('\n--- Testing Math Functions ---');
234
+ console.log('mean:', helpers.math.mean([1, 2, 3, 4, 5]));
235
+ console.log('isPrime (7):', helpers.math.isPrime(7));
236
+ console.log('isPrime (10):', helpers.math.isPrime(10));
237
+ }
238
+
239
+ async function main() {
240
+ await runDatabaseTests();
241
+ runHelperFunctionTests();
242
+ }
243
+
244
+ main();
@@ -1,90 +0,0 @@
1
- const fs = require("fs");
2
- const path = require("path");
3
- const { parse, stringify } = require("csv");
4
-
5
- class CSVDatabase {
6
- constructor(filePath) {
7
- this.filePath = filePath || path.join(__dirname, "database.csv");
8
- if (!fs.existsSync(this.filePath)) {
9
- fs.writeFileSync(this.filePath, "key,value\n"); // Başlık satırı
10
- }
11
- }
12
-
13
- async _readCSV() {
14
- const data = fs.readFileSync(this.filePath, "utf8");
15
- return new Promise((resolve, reject) => {
16
- parse(data, { columns: true }, (err, records) => {
17
- if (err) reject(err);
18
- else resolve(records);
19
- });
20
- });
21
- }
22
-
23
- async _writeCSV(records) {
24
- const data = await new Promise((resolve, reject) => {
25
- stringify(records, { header: true }, (err, output) => {
26
- if (err) reject(err);
27
- else resolve(output);
28
- });
29
- });
30
- fs.writeFileSync(this.filePath, data);
31
- }
32
-
33
- async set(key, value) {
34
- const records = await this._readCSV();
35
- const index = records.findIndex((record) => record.key === key);
36
- if (index !== -1) {
37
- records[index].value = JSON.stringify(value);
38
- } else {
39
- records.push({ key, value: JSON.stringify(value) });
40
- }
41
- await this._writeCSV(records);
42
- }
43
-
44
- async get(key) {
45
- const records = await this._readCSV();
46
- const record = records.find((record) => record.key === key);
47
- return record ? JSON.parse(record.value) : null;
48
- }
49
-
50
- async delete(key) {
51
- const records = await this._readCSV();
52
- const filteredRecords = records.filter((record) => record.key !== key);
53
- await this._writeCSV(filteredRecords);
54
- }
55
-
56
- async has(key) {
57
- const value = await this.get(key);
58
- return value !== null;
59
- }
60
-
61
- async push(key, value) {
62
- const currentValue = (await this.get(key)) || [];
63
- if (!Array.isArray(currentValue)) throw new Error("Value is not an array");
64
- currentValue.push(value);
65
- await this.set(key, currentValue);
66
- }
67
-
68
- async add(key, value) {
69
- const currentValue = (await this.get(key)) || 0;
70
- if (typeof currentValue !== "number") throw new Error("Value is not a number");
71
- await this.set(key, currentValue + value);
72
- }
73
-
74
- async sub(key, value) {
75
- const currentValue = (await this.get(key)) || 0;
76
- if (typeof currentValue !== "number") throw new Error("Value is not a number");
77
- await this.set(key, currentValue - value);
78
- }
79
-
80
- async getAllData() {
81
- const records = await this._readCSV();
82
- const result = {};
83
- records.forEach((record) => {
84
- result[record.key] = JSON.parse(record.value);
85
- });
86
- return result;
87
- }
88
- }
89
-
90
- module.exports = CSVDatabase;
@@ -1,132 +0,0 @@
1
- const fs = require("fs");
2
- const path = require("path");
3
- class database {
4
- constructor(name = "database", loc2) {
5
- var location = "database";
6
- var filePath = `databases/${name}.json`;
7
- if (name.endsWith(".json")) {
8
- filePath = `databases/${name}`;
9
- }
10
- if (location == "database" && !fs.existsSync(`databases`)) {
11
- fs.mkdirSync(`databases`, { recursive: true });
12
- } else if (!fs.existsSync(`${location}`)) {
13
- fs.mkdirSync(`databases`, { recursive: true });
14
- }
15
- if (loc2) {
16
- if (!fs.existsSync(`${loc2}`)) {
17
- fs.mkdirSync(`databases/${loc2}`, { recursive: true });
18
- }
19
- filePath = `databases/${loc2}/${name}.json`;
20
- if (name.endsWith(".json")) {
21
- filePath = `databases/${loc2}/${name}`;
22
- }
23
- }
24
-
25
- if (!fs.existsSync(filePath)) fs.closeSync(fs.openSync(filePath, "w"));
26
- this.FilePath = filePath;
27
- this.Location = location;
28
- }
29
- add(path, value) {
30
- let data = this.get(path);
31
- if (typeof data == "number") data += Number(value);
32
- else data = Number(value);
33
- this.set(path, data);
34
- return data;
35
- }
36
- getAllData() {
37
- let data = this.read();
38
- if (!data) data = {};
39
- return data;
40
- }
41
- get(path) {
42
- let data = this.read(),
43
- result = undefined;
44
- if (!data) data = {};
45
- result = _get(path, data);
46
- return result ? result : undefined;
47
- }
48
- has(path) {
49
- let data = this.read(),
50
- result = undefined;
51
- result = _get(path, data);
52
- if (!result) return false;
53
- else {
54
- return true;
55
- }
56
- }
57
- set(path, value) {
58
- let data = this.read();
59
- if (!data) data = {};
60
- data = _set(path, value, data);
61
- fs.truncateSync(this.FilePath);
62
- fs.writeFileSync(this.FilePath, JSON.stringify(data, null, 4), {
63
- encoding: "utf-8",
64
- });
65
- return data;
66
- }
67
- delete(path) {
68
- let data = this.read();
69
- if (!data) data = {};
70
- data = _set(path, undefined, data);
71
- fs.truncateSync(this.FilePath);
72
- fs.writeFileSync(this.FilePath, JSON.stringify(data, null, 4), {
73
- encoding: "utf-8",
74
- });
75
- return data;
76
- }
77
- push(path, value) {
78
- let data = this.read();
79
- if (!data) data = {};
80
- if (_get(path, data) && Array.isArray(_get(path, data))) {
81
- _get(path, data).push(value);
82
- } else if (!_get(path, data)) {
83
- _set(path, [value], data);
84
- }
85
- fs.truncateSync(this.FilePath);
86
- fs.writeFileSync(this.FilePath, JSON.stringify(data, null, 4), {
87
- encoding: "utf-8",
88
- });
89
- return data;
90
- }
91
- sub(path, value) {
92
- let data = this.get(path);
93
- if (typeof data == "number") data -= Number(value);
94
- else data = Number(value);
95
- this.set(path, data);
96
- return data;
97
- }
98
- read() {
99
- let data = fs.readFileSync(this.FilePath, { encoding: "utf-8" });
100
- if (!data || (data && data == null)) return {};
101
- let obj = JSON.parse(data);
102
-
103
- return obj;
104
- }
105
- }
106
-
107
- function _set(path, value, obj = undefined) {
108
- if (obj == undefined) return undefined;
109
- let locations = path.split("."),
110
- output = {};
111
- output = obj;
112
- let ref = output;
113
- for (let index = 0; index < locations.length - 1; index++) {
114
- if (!ref[locations[index]]) ref = ref[locations[index]] = {};
115
- else ref = ref[locations[index]];
116
- }
117
- ref[locations[locations.length - 1]] = value;
118
- return output;
119
- }
120
-
121
- function _get(path, obj = {}) {
122
- let locations = path.split("."),
123
- ref = obj;
124
- for (let index = 0; index < locations.length - 1; index++) {
125
- ref = ref[locations[index]] ? ref[locations[index]] : undefined;
126
- if (!ref) return undefined;
127
- }
128
- let output = ref[locations[locations.length - 1]];
129
- return output;
130
- }
131
-
132
- module.exports = database;
@@ -1,68 +0,0 @@
1
- const JsonDatabase = require("../jsondatabase/index");
2
- const YamlDatabase = require("../yamldatabase/index"); // Assuming you've saved the YAML class in this path
3
- const MongoDB = require("../mongodb/index");
4
- const MySQLDatabase = require("../mysql/index");
5
- const SQLiteDatabase = require("../sqldb/index");
6
- const RedisDatabase = require("../redis/index");
7
- const PostgreSQL = require("../postgresql/index");
8
-
9
- /**
10
- * Migrates data from one database to another.
11
- * @param {Object} source - Source database configuration.
12
- * @param {Object} target - Target database configuration.
13
- */
14
- async function migrateData(source, target) {
15
- const sourceDb = await initializeDatabase(source);
16
- const targetDb = await initializeDatabase(target);
17
-
18
- const allData = await sourceDb.getAllData();
19
- console.log(allData);
20
-
21
- for (const [key, value] of Object.entries(allData)) {
22
- await targetDb.set(key, value);
23
- }
24
-
25
- console.log(`Migration completed from ${source.type} to ${target.type}`);
26
- }
27
-
28
- /**
29
- * Initializes a database instance based on the configuration.
30
- * @param {Object} config - Database configuration.
31
- * @returns {Object} - Database instance.
32
- */
33
- async function initializeDatabase(config) {
34
- switch (config.type) {
35
- case "json":
36
- return new JsonDatabase(config.options.filePath);
37
- case "yaml":
38
- return new YamlDatabase(config.options.filePath);
39
- case "csv":
40
- return new YamlDatabase(config.options.filePath);
41
- case "mongodb":
42
- const mongoClient = await MongoDB.createData(
43
- config.options.database,
44
- config.options.collection,
45
- config.options.data,
46
- undefined,
47
- config.options.url
48
- );
49
- return mongoClient;
50
- case "mysql":
51
- const mysqlDb = new MySQLDatabase();
52
- await mysqlDb.connect(config.options);
53
- return mysqlDb;
54
- case "sqlite":
55
- return new SQLiteDatabase(config.options.filePath);
56
- case "redis":
57
- const redisDb = new RedisDatabase(config.options);
58
- await redisDb.connect();
59
- return redisDb;
60
- case "postgresql":
61
- return new PostgreSQL(config.options);
62
- default:
63
- throw new Error(`Unsupported database type: ${config.type}`);
64
- }
65
- }
66
-
67
- // Export the migrateData function
68
- module.exports = migrateData;
@@ -1,49 +0,0 @@
1
- const { MongoClient } = require('mongodb');
2
-
3
- const { Client } = require('./src/client/Client.js');
4
- const { Collection } = require("./src/structers/Collection.js");
5
- const { Data } = require("./src/structers/Data.js");
6
- const { Database } = require("./src/structers/Database.js");
7
-
8
-
9
- require('dotenv').config();
10
-
11
- class MongoDB {
12
- /**
13
- * Creates a new client and connects to MongoDB. (Connects to socket)
14
- * @param {String} url
15
- * @param {MongoClientOptions} options
16
- * @return {Promise<Client>}
17
- */
18
- static connect = async function (url, options = undefined) {
19
- const mongoClient = new MongoClient(url, options);
20
- await mongoClient.connect();
21
- return new Client(mongoClient);
22
- }
23
- }
24
-
25
- const justConnect = async (database = 'database',collection ='collection',data='data',options = undefined,url = process.env.MONGODB_URL)=>{
26
- const mongoClient = new MongoClient(url, options);
27
- await mongoClient.connect();
28
- return new Client(mongoClient);
29
- }
30
-
31
- const createDatabase = async (database = 'database',options = undefined,url = process.env.MONGODB_URL)=>{
32
- const mongoClient = new MongoClient(url, options);
33
- await mongoClient.connect();
34
- return new Client(mongoClient).database(database);
35
- }
36
-
37
- const createCollection = async (database = 'database',collection ='collection',options = undefined,url = process.env.MONGODB_URL)=>{
38
- const mongoClient = new MongoClient(url, options);
39
- await mongoClient.connect();
40
- return new Client(mongoClient).database(database).collection(collection);
41
- }
42
-
43
- const createData = async (database = 'database',collection ='collection',data='data',options = undefined,url = process.env.MONGODB_URL)=>{
44
- const mongoClient = new MongoClient(url, options);
45
- await mongoClient.connect();
46
- return new Client(mongoClient).database(database).collection(collection).data(data);
47
- }
48
-
49
- module.exports = { MongoDB, Client, Database, Collection, Data, createDatabase,createCollection,createData,justConnect };
@@ -1,37 +0,0 @@
1
- const mongodb = require("mongodb");
2
- const { Database } = require("../structers/Database.js");
3
-
4
- class Client {
5
- /**
6
- * @type {mongodb.MongoClient}
7
- */
8
- Client;
9
-
10
- /**
11
- * @param {MongoClient} client
12
- */
13
- constructor(client) {
14
- this.Client = client;
15
- }
16
-
17
- /**
18
- * If database does not exists, creates database then returns the database. Otherwise just returns database.
19
- * @param {String} databaseName
20
- * @return {Database}
21
- */
22
- database(databaseName) {
23
- const database = new Database(this.Client, databaseName);
24
- return database;
25
- }
26
-
27
- /**
28
- * Drops the database.
29
- * @param {String} databaseName
30
- * @return {Promise<void>}
31
- */
32
- async dropDatabase(databaseName) {
33
- await this.Client.db(databaseName).dropDatabase();
34
- }
35
- }
36
-
37
- module.exports = { Client };