blackcat.js-database 1.0.4 → 1.0.6

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 CHANGED
@@ -331,6 +331,8 @@ const db = new Database({
331
331
 
332
332
  # JSON Driver (ví dụ)
333
333
 
334
+ Driver lưu dữ liệu trong file json.
335
+
334
336
  ```ts
335
337
  import { Database, JSONDriver } from "blackcat.js-database";
336
338
 
@@ -344,21 +346,35 @@ const database = new Database({
344
346
 
345
347
  # Mongo Driver (ví dụ)
346
348
 
349
+ Driver lưu dữ liệu trong mongoose.
350
+
347
351
  ```ts
348
352
  import { Database, MongoDriver } from "blackcat.js-database";
349
353
 
350
354
  const database = new Database({
351
355
  driver: new MongoDriver({
352
- mongourl: "mongodb://localhost:27017",
353
- databaseName: "mydb",
354
- collectionName: "store"
355
- })
356
+ mongourl: "mongourl",
357
+ databaseName: "BlackCat-Club",
358
+ collectionName: "database-test",
359
+ onLoad: ({ db, collection, databaseName }) => {
360
+ console.log(`✅ Đã kết nối với cơ sở dữ liệu: ${databaseName}`);
361
+ console.log(`📦 Bộ sưu tập: ${collection.collectionName}`);
362
+ // Ví dụ advanced:
363
+ // db.command({ ping: 1 })
364
+ },
365
+ onError: ({ error, databaseName }) => {
366
+ console.error(`❌ Không thể kết nối với cơ sở dữ liệu: ${databaseName}`);
367
+ console.error(error);
368
+ }
369
+ }),
356
370
  });
357
371
  ```
358
372
  ---
359
373
 
360
374
  # SQLite Driver (ví dụ)
361
375
 
376
+ Driver lưu dữ liệu trong SQLite.
377
+
362
378
  ```ts
363
379
  import { Database, SQLiteDriver } from "blackcat.js-database";
364
380
 
@@ -372,7 +388,6 @@ const database = new Database({
372
388
  ---
373
389
 
374
390
 
375
-
376
391
  # Tạo Custom Driver
377
392
 
378
393
  Bạn có thể tạo driver riêng bằng cách implement `DatabaseDriver`.
@@ -5,7 +5,6 @@ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
5
  var __getOwnPropNames = Object.getOwnPropertyNames;
6
6
  var __getProtoOf = Object.getPrototypeOf;
7
7
  var __hasOwnProp = Object.prototype.hasOwnProperty;
8
- var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
9
8
  var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
10
9
  var __export = (target, all) => {
11
10
  for (var name in all)
@@ -28,7 +27,6 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
28
27
  mod
29
28
  ));
30
29
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
31
- var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
32
30
 
33
31
  // src/index.ts
34
32
  var index_exports = {};
@@ -42,12 +40,16 @@ __export(index_exports, {
42
40
  module.exports = __toCommonJS(index_exports);
43
41
 
44
42
  // src/utils/isObject.function.ts
45
- var isObject = /* @__PURE__ */ __name((item) => !Array.isArray(item) && item !== null && typeof item == "object", "isObject");
43
+ var isObject = /* @__PURE__ */ __name((item) => !Array.isArray(item) && item !== null && typeof item === "object", "isObject");
46
44
 
47
45
  // src/utils/typeOf.function.ts
48
46
  var typeOf = /* @__PURE__ */ __name((input) => {
49
- if (input == null || typeof input === "number" && Number.isNaN(input)) return String(input);
50
- if (typeof input === "function" && input.prototype) return `${input.name} class instance`;
47
+ if (input == null || typeof input === "number" && Number.isNaN(input)) {
48
+ return String(input);
49
+ }
50
+ if (typeof input === "function" && input.prototype) {
51
+ return `${input.name} class instance`;
52
+ }
51
53
  return input?.constructor?.name ?? typeof input;
52
54
  }, "typeOf");
53
55
 
@@ -56,23 +58,18 @@ var isNumber = /* @__PURE__ */ __name((input) => !isNaN(input) && input !== "" &
56
58
 
57
59
  // src/utils/BlackCatError.ts
58
60
  var errors = {
59
- DEVICE_IS_OFFLINE: "Your device appears to be offline so it's impossible to proceed with connection to your online MongoDB cluster. Please connect your device to the internet or switch to the local MongoDB database and try again.",
60
- CONNECTION_NOT_ESTABLISHED: "Failed to connect to MongoDB. Please double-check the specified connection URI and make sure that you're performing the database connection using the `QuickMongoClient.connect()` method.",
61
- CONNECTION_URI_NOT_SPECIFIED: "The MongoDB connection URI must be specified.",
62
- INVALID_CONNECTION_URI: "The specified MongoDB connection URI is invalid.",
63
- UNKNOWN_ERROR: "Unknown error.",
64
- REQUIRED_PARAMETER_MISSING: "'{1}' parameter is required but is missing.",
65
- REQUIRED_CONSTRUCTOR_PARAMETER_MISSING: "'{1}' parameter in constructor '{2}' is required but is missing.",
66
- INVALID_CONSTRUCTOR_PARAMETER_TYPE: "'{1}' parameter in constructor '{2}' must be a type of {3}. Received type: {4}.",
67
- INVALID_TYPE: "'{1}' must be a type of {2}. Received type: {3}.",
68
- ONE_OR_MORE_ARRAY_TYPES_INVALID: "All specified elements from array in '{1}' parameter must be a type of {2}. Received array of types: {3}.",
69
- INVALID_TARGET: "The target in database must be a type of {1}. Received target type: {2}.",
70
- INVALID_KEY: "{1}",
71
- INVALID_PARAMETER: "{1} {2}",
72
- DATABASE_CONNECTION_FAILED: "{1}"
61
+ UNKNOWN_ERROR: "L\u1ED7i kh\xF4ng x\xE1c \u0111\u1ECBnh.",
62
+ REQUIRED_PARAMETER_MISSING: "Tham s\u1ED1 '{1}' l\xE0 b\u1EAFt bu\u1ED9c nh\u01B0ng ch\u01B0a \u0111\u01B0\u1EE3c cung c\u1EA5p.",
63
+ INVALID_TYPE: "'{1}' ph\u1EA3i c\xF3 ki\u1EC3u {2}. Ki\u1EC3u nh\u1EADn \u0111\u01B0\u1EE3c: {3}.",
64
+ ONE_OR_MORE_ARRAY_TYPES_INVALID: "T\u1EA5t c\u1EA3 ph\u1EA7n t\u1EED trong m\u1EA3ng c\u1EE7a tham s\u1ED1 '{1}' ph\u1EA3i c\xF3 ki\u1EC3u {2}. C\xE1c ki\u1EC3u nh\u1EADn \u0111\u01B0\u1EE3c trong m\u1EA3ng: {3}.",
65
+ INVALID_TARGET: "\u0110\u1ED1i t\u01B0\u1EE3ng target trong database ph\u1EA3i c\xF3 ki\u1EC3u {1}. Ki\u1EC3u nh\u1EADn \u0111\u01B0\u1EE3c: {2}.",
66
+ INVALID_KEY: "{1}"
73
67
  };
74
68
  var createTypesArray = /* @__PURE__ */ __name((...elements) => `[${elements.map((element) => typeOf(element))}]`, "createTypesArray");
75
- var _BlackCatError = class _BlackCatError extends Error {
69
+ var BlackCatError = class extends Error {
70
+ static {
71
+ __name(this, "BlackCatError");
72
+ }
76
73
  /**
77
74
  * Creates a BlackCatError instance.
78
75
  * @param {string} errorCode Quick Mongo error code.
@@ -89,65 +86,138 @@ var _BlackCatError = class _BlackCatError extends Error {
89
86
  this.name = `BlackCatError [${code}]`;
90
87
  }
91
88
  };
92
- __name(_BlackCatError, "BlackCatError");
93
- var BlackCatError = _BlackCatError;
94
89
 
95
90
  // src/utils/TypedObject.ts
96
- var _TypedObject = class _TypedObject {
91
+ var TypedObject = class {
92
+ static {
93
+ __name(this, "TypedObject");
94
+ }
97
95
  /**
98
- * Returns the names of the enumerable string properties and methods of an object.
96
+ * Lấy danh sách key của object với type chính xác.
97
+ *
98
+ * @typeParam TObject - Kiểu object đầu vào
99
99
  *
100
- * Type parameters:
100
+ * @param obj - Object cần lấy key
101
+ * @returns Mảng các key của object (`ExtractObjectKeys<TObject>[]`)
101
102
  *
102
- * - `TObject` (`Record<string, any>`) - The object to get the object keys types from.
103
+ * @remarks
104
+ * Khác với `Object.keys`:
105
+ * - `Object.keys(obj)` → `string[]`
106
+ * - `TypedObject.keys(obj)` → union key chính xác
107
+ *
108
+ * ---
109
+ *
110
+ * ### Lưu ý:
111
+ * - Nếu `obj` là `null` hoặc `undefined`, sẽ fallback thành `{}` → trả về `[]`
112
+ *
113
+ * ---
114
+ *
115
+ * @example
116
+ * ```ts
117
+ * const obj = { a: 1, b: 2 };
103
118
  *
104
- * @param {TObject} obj Object to get the keys from.
119
+ * const keys = TypedObject.keys(obj);
120
+ * // ("a" | "b")[]
121
+ * ```
105
122
  *
106
- * @returns {Array<ExtractObjectKeys<TObject>>}
107
- * Array of names of the enumerable string properties and methods of the specified object.
123
+ * @see Object.keys
108
124
  */
109
125
  static keys(obj) {
110
126
  return Object.keys(obj || {});
111
127
  }
112
128
  /**
113
- * Returns an array of values of the enumerable properties of an object.
129
+ * Lấy danh sách value của object với type chính xác.
130
+ *
131
+ * @typeParam TObject - Kiểu object đầu vào
132
+ *
133
+ * @param obj - Object cần lấy value
134
+ * @returns Mảng các value của object (`ExtractObjectValues<TObject>[]`)
135
+ *
136
+ * @remarks
137
+ * Khác với `Object.values`:
138
+ * - `Object.values(obj)` → `any[]`
139
+ * - `TypedObject.values(obj)` → union value chính xác
114
140
  *
115
- * Type parameters:
141
+ * ---
116
142
  *
117
- * - `TObject` (`Record<string, any>`) - The object to get the object values types from.
143
+ * ### Lưu ý:
144
+ * - Nếu `obj` là `null` hoặc `undefined`, sẽ fallback thành `{}` → trả về `[]`
118
145
  *
119
- * @param {TObject} obj Object to get the values from.
146
+ * ---
147
+ *
148
+ * @example
149
+ * ```ts
150
+ * const obj = { a: 1, b: 2 };
151
+ *
152
+ * const values = TypedObject.values(obj);
153
+ * // number[]
154
+ * ```
120
155
  *
121
- * @returns {Array<ExtractObjectValues<TObject>>}
122
- * Array of values of the enumerable properties of the specified object.
156
+ * @see Object.values
123
157
  */
124
158
  static values(obj) {
125
159
  return Object.values(obj || {});
126
160
  }
127
161
  /**
128
- * Returns an array of entries (key-value pairs) of the enumerable properties of an object.
162
+ * Lấy danh sách entry (key-value) của object với type chính xác.
129
163
  *
130
- * Type parameters:
164
+ * @typeParam TObject - Kiểu object đầu vào
131
165
  *
132
- * - `TObject` (`Record<string, any>`) - The object to get the object entries types (key-value pairs types) from.
166
+ * @param obj - Object cần lấy entries
167
+ * @returns Mảng các cặp `[key, value]` (`ExtractObjectEntries<TObject>[]`)
133
168
  *
134
- * @param {TObject} obj Object to get the entries from.
169
+ * @remarks
170
+ * Khác với `Object.entries`:
171
+ * - `Object.entries(obj)` → `[string, any][]`
172
+ * - `TypedObject.entries(obj)` → typed tuple chính xác
135
173
  *
136
- * @returns {ExtractObjectEntries<TObject>[]}
137
- * Array of entries (key-value pairs) of the enumerable properties of the specified object.
174
+ * ---
175
+ *
176
+ * ### Lưu ý:
177
+ * - Nếu `obj` là `null` hoặc `undefined`, sẽ fallback thành `{}` → trả về `[]`
178
+ *
179
+ * ---
180
+ *
181
+ * @example
182
+ * ```ts
183
+ * const obj = { a: 1, b: 2 };
184
+ *
185
+ * const entries = TypedObject.entries(obj);
186
+ * // ["a" | "b", number][]
187
+ * ```
188
+ *
189
+ * @example
190
+ * ```ts
191
+ * for (const [key, value] of TypedObject.entries(obj)) {
192
+ * // key & value được infer đúng type
193
+ * }
194
+ * ```
195
+ *
196
+ * @see Object.entries
138
197
  */
139
198
  static entries(obj) {
140
199
  return Object.entries(obj || {});
141
200
  }
142
201
  };
143
- __name(_TypedObject, "TypedObject");
144
- var TypedObject = _TypedObject;
145
-
146
- // src/utils/Emitter.ts
147
- var import_node_events = require("events");
148
202
 
149
203
  // src/Database.ts
150
- var _Database = class _Database {
204
+ var Database = class {
205
+ static {
206
+ __name(this, "Database");
207
+ }
208
+ /**
209
+ * Storage driver được sử dụng để đọc và ghi dữ liệu database.
210
+ *
211
+ * Driver phải implement interface `DatabaseDriver`.
212
+ *
213
+ * Ví dụ:
214
+ * ```ts
215
+ * const db = new Database({
216
+ * driver: new JSONDriver({ filePath: "./database.json" }),
217
+ * })
218
+ * ```
219
+ */
220
+ driver;
151
221
  /**
152
222
  * Khởi tạo Database instance.
153
223
  *
@@ -173,19 +243,6 @@ var _Database = class _Database {
173
243
  * ```
174
244
  */
175
245
  constructor(options) {
176
- /**
177
- * Storage driver được sử dụng để đọc và ghi dữ liệu database.
178
- *
179
- * Driver phải implement interface `DatabaseDriver`.
180
- *
181
- * Ví dụ:
182
- * ```ts
183
- * const db = new Database({
184
- * driver: new JSONDriver({ filePath: "./database.json" }),
185
- * })
186
- * ```
187
- */
188
- __publicField(this, "driver");
189
246
  this.driver = options.driver;
190
247
  }
191
248
  /**
@@ -234,7 +291,6 @@ var _Database = class _Database {
234
291
  */
235
292
  async get(key) {
236
293
  const data = await this.all();
237
- if (key === void 0) return data;
238
294
  if (typeof key !== "string") {
239
295
  throw new BlackCatError("INVALID_TYPE", "key", "string", typeOf(key));
240
296
  }
@@ -323,7 +379,7 @@ var _Database = class _Database {
323
379
  * @param {AutocompletableString<P>} key Đường dẫn dữ liệu cần gán giá trị.
324
380
  * @param {ObjectValue<V, P>} value Giá trị mới.
325
381
  *
326
- * @returns {Promise<If<IsObject<V>, ObjectValue<V, FirstObjectKey<P>>, V>>} Giá trị vừa được set hoặc object root nếu value là object.
382
+ * @returns {void} Giá trị vừa được set hoặc object root nếu value là object.
327
383
  *
328
384
  * @example
329
385
  * ```ts
@@ -358,7 +414,6 @@ var _Database = class _Database {
358
414
  }
359
415
  ;
360
416
  await this.driver.set(allDatabase);
361
- return typeof value == "object" && value !== null ? await this.get(keys[0]) : value;
362
417
  }
363
418
  /**
364
419
  * Xóa một key khỏi database.
@@ -575,7 +630,8 @@ var _Database = class _Database {
575
630
  if (!isNumber(numberToAdd)) {
576
631
  throw new BlackCatError("INVALID_TYPE", "numberToAdd", "number", typeOf(numberToAdd));
577
632
  }
578
- return await this.set(key, targetNumber + numberToAdd);
633
+ await this.set(key, targetNumber + numberToAdd);
634
+ return targetNumber + numberToAdd;
579
635
  }
580
636
  /**
581
637
  * Trừ giá trị khỏi một key dạng number.
@@ -605,7 +661,8 @@ var _Database = class _Database {
605
661
  if (!isNumber(numberToSubtract)) {
606
662
  throw new BlackCatError("INVALID_TYPE", "numberToSubtract", "number", typeOf(numberToSubtract));
607
663
  }
608
- return await this.set(key, targetNumber - numberToSubtract);
664
+ await this.set(key, targetNumber - numberToSubtract);
665
+ return targetNumber - numberToSubtract;
609
666
  }
610
667
  /**
611
668
  * Thêm một hoặc nhiều phần tử vào cuối array tại key-path.
@@ -823,7 +880,8 @@ var _Database = class _Database {
823
880
  * const userKeys = await db.keys("user");
824
881
  */
825
882
  async keys(key) {
826
- if (!key) return TypedObject.keys(await this.all());
883
+ const all = await this.all();
884
+ if (!key) return TypedObject.keys(all);
827
885
  const data = await this.get(key);
828
886
  return TypedObject.keys(data).filter((key2) => data[key2] !== void 0 && data[key2] !== null);
829
887
  }
@@ -857,7 +915,8 @@ var _Database = class _Database {
857
915
  * const userValues = await db.values("users");
858
916
  */
859
917
  async values(key) {
860
- if (!key) return TypedObject.values(await this.all());
918
+ const all = await this.all();
919
+ if (!key) return TypedObject.values(all);
861
920
  const data = await this.get(key);
862
921
  return TypedObject.values(data);
863
922
  }
@@ -982,12 +1041,21 @@ var _Database = class _Database {
982
1041
  return values.every(queryFunction);
983
1042
  }
984
1043
  };
985
- __name(_Database, "Database");
986
- var Database = _Database;
987
1044
 
988
1045
  // src/drivers/JSONDriver.ts
989
1046
  var import_fs = require("fs");
990
- var _JSONDriver = class _JSONDriver {
1047
+ var JSONDriver = class {
1048
+ static {
1049
+ __name(this, "JSONDriver");
1050
+ }
1051
+ /**
1052
+ * Đường dẫn tới file database JSON.
1053
+ */
1054
+ filePath;
1055
+ /**
1056
+ * Cho biết có minify JSON khi ghi file hay không.
1057
+ */
1058
+ minifyJSON;
991
1059
  /**
992
1060
  * Khởi tạo một instance mới của {@link JSONDriver}.
993
1061
  *
@@ -1009,14 +1077,6 @@ var _JSONDriver = class _JSONDriver {
1009
1077
  * ```
1010
1078
  */
1011
1079
  constructor(options) {
1012
- /**
1013
- * Đường dẫn tới file database JSON.
1014
- */
1015
- __publicField(this, "filePath");
1016
- /**
1017
- * Cho biết có minify JSON khi ghi file hay không.
1018
- */
1019
- __publicField(this, "minifyJSON");
1020
1080
  this.filePath = options.filePath || "database.json";
1021
1081
  this.minifyJSON = options.minifyJSON || false;
1022
1082
  }
@@ -1077,11 +1137,16 @@ var _JSONDriver = class _JSONDriver {
1077
1137
  return true;
1078
1138
  }
1079
1139
  };
1080
- __name(_JSONDriver, "JSONDriver");
1081
- var JSONDriver = _JSONDriver;
1082
1140
 
1083
1141
  // src/drivers/MemoryDriver.ts
1084
- var _MemoryDriver = class _MemoryDriver {
1142
+ var MemoryDriver = class {
1143
+ static {
1144
+ __name(this, "MemoryDriver");
1145
+ }
1146
+ /**
1147
+ * Object chứa toàn bộ dữ liệu database trong RAM.
1148
+ */
1149
+ store;
1085
1150
  /**
1086
1151
  * Khởi tạo MemoryDriver.
1087
1152
  *
@@ -1108,10 +1173,6 @@ var _MemoryDriver = class _MemoryDriver {
1108
1173
  * ```
1109
1174
  */
1110
1175
  constructor(initialData = {}) {
1111
- /**
1112
- * Object chứa toàn bộ dữ liệu database trong RAM.
1113
- */
1114
- __publicField(this, "store");
1115
1176
  this.store = initialData;
1116
1177
  }
1117
1178
  /**
@@ -1142,12 +1203,21 @@ var _MemoryDriver = class _MemoryDriver {
1142
1203
  return true;
1143
1204
  }
1144
1205
  };
1145
- __name(_MemoryDriver, "MemoryDriver");
1146
- var MemoryDriver = _MemoryDriver;
1147
1206
 
1148
1207
  // src/drivers/SQLiteDriver.ts
1149
1208
  var import_better_sqlite3 = __toESM(require("better-sqlite3"));
1150
- var _SQLiteDriver = class _SQLiteDriver {
1209
+ var SQLiteDriver = class {
1210
+ static {
1211
+ __name(this, "SQLiteDriver");
1212
+ }
1213
+ /**
1214
+ * SQLite database instance.
1215
+ */
1216
+ db;
1217
+ /**
1218
+ * Tên table lưu trữ dữ liệu JSON.
1219
+ */
1220
+ table;
1151
1221
  /**
1152
1222
  * Khởi tạo SQLiteDriver.
1153
1223
  *
@@ -1164,14 +1234,6 @@ var _SQLiteDriver = class _SQLiteDriver {
1164
1234
  * ```
1165
1235
  */
1166
1236
  constructor(options = {}) {
1167
- /**
1168
- * SQLite database instance.
1169
- */
1170
- __publicField(this, "db");
1171
- /**
1172
- * Tên table lưu trữ dữ liệu JSON.
1173
- */
1174
- __publicField(this, "table");
1175
1237
  this.db = new import_better_sqlite3.default(options.filePath ?? "database.sqlite");
1176
1238
  this.table = options.table ?? "json_store";
1177
1239
  this.db.prepare(`CREATE TABLE IF NOT EXISTS ${this.table} (id INTEGER PRIMARY KEY, data TEXT)`).run();
@@ -1209,12 +1271,45 @@ var _SQLiteDriver = class _SQLiteDriver {
1209
1271
  return true;
1210
1272
  }
1211
1273
  };
1212
- __name(_SQLiteDriver, "SQLiteDriver");
1213
- var SQLiteDriver = _SQLiteDriver;
1214
1274
 
1215
1275
  // src/drivers/MongoDriver.ts
1216
1276
  var import_mongodb = require("mongodb");
1217
- var _MongoDriver = class _MongoDriver {
1277
+ var MongoDriver = class {
1278
+ static {
1279
+ __name(this, "MongoDriver");
1280
+ }
1281
+ /**
1282
+ * MongoDB client instance.
1283
+ */
1284
+ client;
1285
+ /**
1286
+ * MongoDB database instance.
1287
+ */
1288
+ db;
1289
+ /**
1290
+ * Collection lưu dữ liệu JSON.
1291
+ */
1292
+ collection;
1293
+ /**
1294
+ * Tên database MongoDB.
1295
+ */
1296
+ databaseName;
1297
+ /**
1298
+ * Tên collection MongoDB.
1299
+ */
1300
+ collectionName;
1301
+ /**
1302
+ * Callback khi kết nối thành công.
1303
+ */
1304
+ onLoad;
1305
+ /**
1306
+ * Callback khi xảy ra lỗi.
1307
+ */
1308
+ onError;
1309
+ /**
1310
+ * Trạng thái đã gọi onLoad chưa (tránh spam)
1311
+ */
1312
+ isLoaded = false;
1218
1313
  /**
1219
1314
  * Khởi tạo MongoDriver.
1220
1315
  *
@@ -1222,35 +1317,25 @@ var _MongoDriver = class _MongoDriver {
1222
1317
  *
1223
1318
  * @example
1224
1319
  * ```ts
1320
+ * import { Database, MongoDriver } from "blackcat.js-database";
1321
+ *
1225
1322
  * const database = new Database({
1226
1323
  * driver: new MongoDriver({
1227
1324
  * mongourl: "mongodb://localhost:27017",
1228
1325
  * databaseName: "mydb",
1229
- * collectionName: "store"
1326
+ * collectionName: "store",
1327
+ * onLoad: ({ db, collection, databaseName }) => {
1328
+ * console.log(`✅ Đã kết nối với cơ sở dữ liệu: ${databaseName}`);
1329
+ * console.log(`📦 Bộ sưu tập: ${collection.collectionName}`);
1330
+ * },
1331
+ * onError: ({ error, databaseName }) => {
1332
+ * console.error(`❌ Không thể kết nối với cơ sở dữ liệu: ${databaseName}`);
1333
+ * console.error(error);
1334
+ * }
1230
1335
  * })
1231
1336
  * });
1232
1337
  */
1233
1338
  constructor(options = {}) {
1234
- /**
1235
- * MongoDB client instance.
1236
- */
1237
- __publicField(this, "client");
1238
- /**
1239
- * MongoDB database instance.
1240
- */
1241
- __publicField(this, "db");
1242
- /**
1243
- * Collection lưu dữ liệu JSON.
1244
- */
1245
- __publicField(this, "collection");
1246
- /**
1247
- * Tên database MongoDB.
1248
- */
1249
- __publicField(this, "databaseName");
1250
- /**
1251
- * Tên collection MongoDB.
1252
- */
1253
- __publicField(this, "collectionName");
1254
1339
  const {
1255
1340
  mongourl = "mongodb://localhost:27017",
1256
1341
  databaseName = "database",
@@ -1259,21 +1344,42 @@ var _MongoDriver = class _MongoDriver {
1259
1344
  this.client = new import_mongodb.MongoClient(mongourl);
1260
1345
  this.databaseName = databaseName;
1261
1346
  this.collectionName = collectionName;
1347
+ this.onLoad = options.onLoad;
1348
+ this.onError = options.onError;
1262
1349
  }
1263
1350
  /**
1264
1351
  * Thiết lập kết nối MongoDB nếu chưa kết nối.
1265
1352
  */
1266
1353
  async connect() {
1267
1354
  if (!this.db) {
1268
- await this.client.connect();
1269
- this.db = this.client.db(this.databaseName);
1270
- this.collection = this.db.collection(this.collectionName);
1271
- const doc = await this.collection.findOne({ _id: "database" });
1272
- if (!doc) {
1273
- await this.collection.insertOne({
1274
- _id: "database",
1275
- data: {}
1355
+ try {
1356
+ await this.client.connect();
1357
+ this.db = this.client.db(this.databaseName);
1358
+ this.collection = this.db.collection(this.collectionName);
1359
+ const doc = await this.collection.findOne({ _id: "database" });
1360
+ if (!doc) {
1361
+ await this.collection.insertOne({
1362
+ _id: "database",
1363
+ data: {}
1364
+ });
1365
+ }
1366
+ if (!this.isLoaded) {
1367
+ this.isLoaded = true;
1368
+ this.onLoad?.({
1369
+ client: this.client,
1370
+ db: this.db,
1371
+ collection: this.collection,
1372
+ databaseName: this.databaseName,
1373
+ collectionName: this.collectionName
1374
+ });
1375
+ }
1376
+ } catch (error) {
1377
+ this.onError?.({
1378
+ error,
1379
+ databaseName: this.databaseName,
1380
+ collectionName: this.collectionName
1276
1381
  });
1382
+ throw error;
1277
1383
  }
1278
1384
  }
1279
1385
  }
@@ -1313,8 +1419,6 @@ var _MongoDriver = class _MongoDriver {
1313
1419
  return true;
1314
1420
  }
1315
1421
  };
1316
- __name(_MongoDriver, "MongoDriver");
1317
- var MongoDriver = _MongoDriver;
1318
1422
  // Annotate the CommonJS export names for ESM import in node:
1319
1423
  0 && (module.exports = {
1320
1424
  Database,
@@ -1323,4 +1427,4 @@ var MongoDriver = _MongoDriver;
1323
1427
  MongoDriver,
1324
1428
  SQLiteDriver
1325
1429
  });
1326
- //# sourceMappingURL=index.js.map
1430
+ //# sourceMappingURL=index.cjs.map