blackcat.js-database 1.0.0-test → 1.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.
package/dist/index.js CHANGED
@@ -1,7 +1,9 @@
1
1
  "use strict";
2
+ var __create = Object.create;
2
3
  var __defProp = Object.defineProperty;
3
4
  var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
5
  var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
5
7
  var __hasOwnProp = Object.prototype.hasOwnProperty;
6
8
  var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
7
9
  var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
@@ -17,6 +19,14 @@ var __copyProps = (to, from, except, desc) => {
17
19
  }
18
20
  return to;
19
21
  };
22
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
23
+ // If the importer is in node compatibility mode or this is not an ESM
24
+ // file that has been converted to a CommonJS file using a Babel-
25
+ // compatible transform (i.e. "__esModule" has not been set), then set
26
+ // "default" to the CommonJS "module.exports" for node compatibility.
27
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
28
+ mod
29
+ ));
20
30
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
21
31
  var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
22
32
 
@@ -24,7 +34,10 @@ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "sy
24
34
  var index_exports = {};
25
35
  __export(index_exports, {
26
36
  Database: () => Database,
27
- JSONDriver: () => JSONDriver
37
+ JSONDriver: () => JSONDriver,
38
+ MemoryDriver: () => MemoryDriver,
39
+ MongoDriver: () => MongoDriver,
40
+ SQLiteDriver: () => SQLiteDriver
28
41
  });
29
42
  module.exports = __toCommonJS(index_exports);
30
43
 
@@ -135,170 +148,192 @@ var import_node_events = require("events");
135
148
 
136
149
  // src/Database.ts
137
150
  var _Database = class _Database {
151
+ /**
152
+ * Khởi tạo Database instance.
153
+ *
154
+ * @param options Cấu hình database.
155
+ * @param options.driver Driver lưu trữ dữ liệu.
156
+ *
157
+ * @example
158
+ * ```ts
159
+ * const db = new Database({
160
+ * driver: new JSONDriver({ filePath: "./database.json" }),
161
+ * })
162
+ * ```
163
+ *
164
+ * Ví dụ với MongoDB:
165
+ *
166
+ * ```ts
167
+ * const db = new Database({
168
+ * driver: new MongoDriver({
169
+ * uri: "mongodb://localhost:27017",
170
+ * databaseName: "mydb"
171
+ * })
172
+ * });
173
+ * ```
174
+ */
138
175
  constructor(options) {
139
176
  /**
140
- * The low-level database driver handling basic operations.
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
+ * ```
141
187
  */
142
188
  __publicField(this, "driver");
143
189
  this.driver = options.driver;
144
190
  }
145
191
  /**
146
- * Gets all the database contents from the cache.
192
+ * Lấy toàn bộ dữ liệu từ database thông qua driver.
147
193
  *
148
- * Type parameters:
194
+ * @template T Kiểu dữ liệu object database trả về.
149
195
  *
150
- * - `T` (`object`, defaults to `Record<string, any>`) - The type of object of all the database object to be returned.
151
- *
152
- * @returns {T} Cached database contents.
153
- *
154
- * @template T (object, defaults to `Record<string, any>`) -
155
- * The type of object of all the database object to be returned.
196
+ * @returns Promise chứa toàn bộ dữ liệu database.
156
197
  *
157
198
  * @example
158
- * const databaseContents = await database.all();
159
- * console.log(databaseContents); // -> { ... (the object of all the data stored in database) }
199
+ * ```ts
200
+ * const data = await db.all();
201
+ * console.log(data.users);
202
+ * ```
160
203
  */
161
204
  async all() {
162
- const allDatabase = await this.driver.all();
163
- return allDatabase;
205
+ return await this.driver.all();
164
206
  }
165
207
  /**
166
- * Retrieves a value from database by a key.
208
+ * Lấy giá trị từ database theo key-path.
167
209
  *
168
- * @param {AutocompletableString<P>} key The key to access the target in database by.
169
- * @returns {Maybe<ObjectValue<V, P>>} The value of the target in database.
210
+ * Key thể chuỗi dạng path:
170
211
  *
171
- * @example
172
- * const simpleValue = await database.get("simpleValue");
173
- * console.log(simpleValue); // -> 123
212
+ * ```
213
+ * user.profile.name
214
+ * economy.users.123.balance
215
+ * ```
216
+ *
217
+ * Nếu không truyền `key`, method sẽ trả về **toàn bộ database**.
218
+ *
219
+ * @template {AutocompletableString<ObjectPath<V>>} P Key path trong database.
174
220
  *
175
- * const databaseObjectPropertyAccessed = await database.get("youCanAlso.accessDatabaseObjectProperties.likeThat");
176
- * console.log(databaseObjectPropertyAccessed); // -> "hello world!"
221
+ * @param {AutocompletableString<P>} key Đường dẫn dữ liệu cần lấy.
177
222
  *
178
- * // Assuming that the initial database object for this example is:
179
- * // {
180
- * // simpleValue: 123,
181
- * // youCanAlso: {
182
- * // accessDatabaseObjectProperties: {
183
- * // likeThat: "hello world!"
184
- * // }
185
- * // }
186
- * // }
223
+ * @returns Giá trị tại key hoặc `null` nếu không tồn tại.
224
+ *
225
+ * @example
226
+ * ```ts
227
+ * const name = await db.get("user.profile.name");
228
+ * ```
229
+ *
230
+ * @example
231
+ * ```ts
232
+ * const all = await db.get();
233
+ * ```
187
234
  */
188
235
  async get(key) {
189
- if (key !== void 0) {
190
- if (typeof key !== "string") {
191
- throw new BlackCatError("INVALID_TYPE", "key", "string", typeOf(key));
192
- }
193
- return this.driver.get(key);
194
- } else {
195
- return this.all();
236
+ const data = await this.all();
237
+ if (key === void 0) return data;
238
+ if (typeof key !== "string") {
239
+ throw new BlackCatError("INVALID_TYPE", "key", "string", typeOf(key));
196
240
  }
197
- ;
241
+ const keys = key.split(".");
242
+ let result = data;
243
+ for (const k of keys) {
244
+ if (!isObject(result) && !Array.isArray(result)) return null;
245
+ result = result[k];
246
+ if (result === void 0) return null;
247
+ }
248
+ return result;
198
249
  }
199
250
  /**
200
- * Retrieves a value from database by a key.
201
- *
202
- * - This method is an alias for {@link Database.get()} method.
251
+ * Tìm trả về một bản ghi đầu tiên khớp với điều kiện trong database.
203
252
  *
204
- * @param {AutocompletableString<P>} key The key to access the target in database by.
205
- * @returns {Maybe<ObjectValue<V, P>>} The value from database.
253
+ * Hàm này hai cách sử dụng:
206
254
  *
207
- * @example
208
- * const simpleValue = await database.fetch("simpleValue");
209
- * console.log(simpleValue); // -> 123
255
+ * 1. **Chỉ truyền `key`**
256
+ * Trả về toàn bộ dữ liệu của key (tương tự `get()`).
210
257
  *
211
- * // You can use the dot notation to access the database object properties:
212
- * const playerInventory = await database.fetch("player.inventory");
213
- * console.log(playerInventory); // -> []
258
+ * 2. **Truyền `key` `query`**
259
+ * Tìm phần tử đầu tiên trong mảng dữ liệu của key khớp với điều kiện.
214
260
  *
215
- * // Assuming that the initial database object for this example is:
216
- * // {
217
- * // simpleValue: 123,
218
- * // player: {
219
- * // inventory: []
220
- * // }
221
- * // }
222
- */
223
- async fetch(key) {
224
- return this.get(key);
225
- }
226
- /**
227
- * Determines if the data is stored in database.
228
- * @param {AutocompletableString<P>} key The key to access the target in database by.
229
- * @returns {boolean} Whether the data is stored in database.
261
+ * @template V - Kiểu dữ liệu của database.
262
+ * @template P - Đường dẫn key trong object (`ObjectPath<V>`).
230
263
  *
231
- * @example
232
- * const isSimpleValueInDatabase = await database.has("simpleValue");
233
- * console.log(isSimpleValueInDatabase); // -> true
264
+ * @param key - Key hoặc đường dẫn đến dữ liệu cần truy vấn.
265
+ * @param query - Đối tượng điều kiện để tìm bản ghi phù hợp.
234
266
  *
235
- * const somethingElse = await database.has("somethingElse");
236
- * console.log(somethingElse); // -> false
267
+ * @returns
268
+ * - Nếu chỉ có `key`: trả về toàn bộ dữ liệu của key.
269
+ * - Nếu có `query`: trả về bản ghi đầu tiên khớp điều kiện.
270
+ * - Nếu không tìm thấy: trả về `null`.
237
271
  *
238
- * // You can use the dot notation to check the database object properties:
239
- * const isObjectInDatabase = await database.has("youCanAlso.accessObjectProperties.likeThat");
240
- * console.log(isObjectInDatabase); // -> true
272
+ * @example
273
+ * Chỉ lấy dữ liệu theo key
274
+ * ```ts
275
+ * const users = await db.findOne("user");
276
+ * ```
241
277
  *
242
- * // Assuming that the initial database object for this example is:
243
- * // {
244
- * // simpleValue: 123,
245
- * // player: {
246
- * // inventory: []
247
- * // },
248
- * // youCanAlso: {
249
- * // accessObjectProperties: {
250
- * // likeThat: "hello world!"
251
- * // }
252
- * // }
253
- * // }
278
+ * @example
279
+ * Tìm một bản ghi theo điều kiện
280
+ * ```ts
281
+ * const user = await db.findOne("user", {
282
+ * guild: 1234566
283
+ * });
284
+ * ```
254
285
  */
255
- async has(key) {
256
- return this.get(key) !== null && this.get(key) !== void 0;
286
+ async findOne(key, query) {
287
+ const data = await this.get(key);
288
+ if (!query) return data;
289
+ if (!Array.isArray(data)) return null;
290
+ const result = data.find((item) => {
291
+ return Object.entries(query).every(([k, v]) => item[k] == v);
292
+ });
293
+ return result ?? null;
257
294
  }
258
295
  /**
259
- * Writes the specified value into database under the specified key.
296
+ * Kiểm tra một key-path tồn tại trong database hay không.
260
297
  *
261
- * @param {AutocompletableString<P>} key The key to write in the target.
262
- * @param {ObjectValue<V, P>} value The value to write.
298
+ * Method này sử dụng `get()` để xác định giá trị có tồn tại.
263
299
  *
264
- * @returns {Promise<If<IsObject<V>, FirstObjectKey<P>, V>>}
265
- * - If the `value` parameter's type is not an object (string, number, boolean, etc), then the specified
266
- * `value` parameter (type of `ObjectValue<V, P>`) will be returned.
300
+ * @template {AutocompletableString<ObjectPath<V>>} P Key path trong database.
267
301
  *
268
- * - If an object is specified in the `value` parameter, then the object of the first key will be returned.
269
- * (type of `FirstObjectKey<P>` - first object key (e.g. in key `member.user.id`, the first key will be `member`))
302
+ * @param {AutocompletableString<P>} key Đường dẫn dữ liệu cần kiểm tra.
270
303
  *
271
- * @example
272
- * // Assuming that the initial database object for this example is empty.
304
+ * @returns `true` nếu key tồn tại, ngược lại `false`.
273
305
  *
274
- * await database.set("something", "hello");
275
- * const hello = await database.get("something");
306
+ * @example
307
+ * ```ts
308
+ * const exists = await db.has("users.123");
309
+ * ```
310
+ */
311
+ async has(key) {
312
+ const value = await this.get(key);
313
+ return value !== null && value !== void 0;
314
+ }
315
+ /**
316
+ * Gán giá trị cho một key-path trong database.
276
317
  *
277
- * console.log(hello); // -> "hello"
318
+ * Nếu key-path chưa tồn tại, các object trung gian
319
+ * sẽ được tự động tạo.
278
320
  *
279
- * // You can use the dot notation to write data in objects:
280
- * const dotNotationSetResult = await database.set("member.user.id", 2000);
281
- * console.log(dotNotationSetResult); // -> 2000
321
+ * @template {AutocompletableString<ObjectPath<V>>} P Key path trong database.
282
322
  *
283
- * await database.set("member.inventory", []);
284
- * const inventory = await database.get("member.inventory");
323
+ * @param {AutocompletableString<P>} key Đường dẫn dữ liệu cần gán giá trị.
324
+ * @param {ObjectValue<V, P>} value Giá trị mới.
285
325
  *
286
- * console.log(inventory); // -> []
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.
287
327
  *
288
- * // Using objects as value will return the object of key `thats`:
289
- * await database.set("member.user", { name: "Jerry" }); // -> { member: { user: { name: "Jerry" } } }
328
+ * @example
329
+ * ```ts
330
+ * await db.set("users.123.name", "Alice");
331
+ * ```
290
332
  *
291
- * // After these manipulations, the database object will look like this:
292
- * // {
293
- * // "something": "hello",
294
- * // "member": {
295
- * // "inventory": [],
296
- * // "user": {
297
- * // "name": "Jerry",
298
- * // "id": 2000
299
- * // }
300
- * // }
301
- * // }
333
+ * @example
334
+ * ```ts
335
+ * await db.set("config.prefix", "!");
336
+ * ```
302
337
  */
303
338
  async set(key, value) {
304
339
  const allDatabase = await this.all();
@@ -322,21 +357,134 @@ var _Database = class _Database {
322
357
  ;
323
358
  }
324
359
  ;
325
- await this.driver.set(keys[0], allDatabase);
360
+ await this.driver.set(allDatabase);
326
361
  return typeof value == "object" && value !== null ? await this.get(keys[0]) : value;
327
362
  }
328
363
  /**
329
- * Update the specified value into database under the specified key.
364
+ * Xóa một key khỏi database.
365
+ *
366
+ * Hỗ trợ nested path bằng dot notation.
367
+ *
368
+ * @typeParam P - Path của object.
369
+ *
370
+ * @param key - Đường dẫn key cần xóa.
371
+ *
372
+ * @returns
373
+ * - `true` nếu xóa thành công
374
+ * - `false` nếu key không tồn tại
375
+ *
376
+ * @throws BlackCatError
377
+ * - INVALID_TYPE nếu key không phải string
378
+ *
379
+ * @example
380
+ * await db.delete("user.name");
381
+ */
382
+ async delete(key) {
383
+ if (typeof key !== "string") {
384
+ throw new BlackCatError("INVALID_TYPE", "key", "string", typeof key);
385
+ }
386
+ const allDatabase = await this.all();
387
+ const keys = key.split(".");
388
+ const lastKey = keys.pop();
389
+ let currentObj = allDatabase;
390
+ for (const k of keys) {
391
+ if (!isObject(currentObj[k])) {
392
+ return false;
393
+ }
394
+ currentObj = currentObj[k];
395
+ }
396
+ if (!(lastKey in currentObj)) return false;
397
+ delete currentObj[lastKey];
398
+ await this.driver.set(allDatabase);
399
+ return true;
400
+ }
401
+ /**
402
+ * Xóa toàn bộ dữ liệu trong database.
403
+ *
404
+ * Method này gọi trực tiếp `driver.delete()` để reset storage.
405
+ *
406
+ * @returns `true` sau khi dữ liệu đã được xóa.
407
+ *
408
+ * @example
409
+ * await db.deleteAll();
410
+ */
411
+ async deleteAll() {
412
+ await this.driver.delete();
413
+ return true;
414
+ }
415
+ /**
416
+ * Xóa nhiều bản ghi trong một mảng dữ liệu dựa trên điều kiện truy vấn.
417
+ *
418
+ * ⚠️ Method này **chỉ hoạt động với dữ liệu dạng mảng (array)**.
419
+ * Nếu dữ liệu tại `key` không phải là mảng, method sẽ **không thực hiện xóa**
420
+ * và trả về `0`.
330
421
  *
331
- * @param {AutocompletableString<P>} key The key to update the target.
332
- * @param {ObjectValue<V, P>} value The value to update.
422
+ * Method sẽ duyệt qua toàn bộ phần tử trong mảng và xóa những phần tử
423
+ * khớp với điều kiện `query`.
333
424
  *
334
- * @returns {Promise<If<IsObject<V>, FirstObjectKey<P>, V>>}
335
- * - If the `value` parameter's type is not an object (string, number, boolean, etc), then the specified
336
- * `value` parameter (type of `ObjectValue<V, P>`) will be returned.
425
+ * @template V - Kiểu dữ liệu của database.
426
+ * @template P - Đường dẫn key trong object (`ObjectPath<V>`).
337
427
  *
338
- * - If an object is specified in the `value` parameter, then the object of the first key will be returned.
339
- * (type of `FirstObjectKey<P>` - first object key (e.g. in key `member.user.id`, the first key will be `member`))
428
+ * @param key - Đường dẫn đến mảng dữ liệu cần thao tác.
429
+ * @param query - Điều kiện để xác định các phần tử cần xóa.
430
+ * Có thể truyền:
431
+ * - Một object điều kiện
432
+ *
433
+ * @returns Số lượng phần tử đã bị xóa khỏi mảng.
434
+ *
435
+ * @example
436
+ * Database mẫu:
437
+ * ```json
438
+ * {
439
+ * "member": {
440
+ * "user": {
441
+ * "database": [
442
+ * { "guild": "123", "username": "vinh" },
443
+ * { "guild": "456", "username": "test" }
444
+ * ]
445
+ * }
446
+ * }
447
+ * }
448
+ * ```
449
+ *
450
+ * @example
451
+ * Xóa tất cả user có guild = "123"
452
+ * ```ts
453
+ * await db.deleteMany("member.user.database", {
454
+ * guild: "123"
455
+ * });
456
+ * ```
457
+ */
458
+ async deleteMany(key, query) {
459
+ const data = await this.get(key);
460
+ if (!Array.isArray(data)) return 0;
461
+ const originalLength = data.length;
462
+ const filtered = data.filter((item) => {
463
+ return !Object.entries(query).every(([k, v]) => item[k] == v);
464
+ });
465
+ await this.set(key, filtered);
466
+ return originalLength - filtered.length;
467
+ }
468
+ /**
469
+ * Cập nhật giá trị của một key-path trong database.
470
+ *
471
+ * Khác với `set()`, method này chỉ ghi đè giá trị của key cuối cùng
472
+ * trong path mà không thay đổi cấu trúc object phía trên.
473
+ *
474
+ * Nếu các object trung gian trong path chưa tồn tại
475
+ * thì chúng sẽ được tự động tạo.
476
+ *
477
+ * @template P Key path trong database.
478
+ *
479
+ * @param key Đường dẫn dữ liệu cần cập nhật.
480
+ * @param value Giá trị mới.
481
+ *
482
+ * @returns Object cha của key vừa cập nhật.
483
+ *
484
+ * @example
485
+ * ```ts
486
+ * await db.update("users.123.name", "Alice");
487
+ * ```
340
488
  */
341
489
  async update(key, value) {
342
490
  const allDatabase = await this.all();
@@ -351,34 +499,25 @@ var _Database = class _Database {
351
499
  }
352
500
  const lastKey = keys[keys.length - 1];
353
501
  current[lastKey] = value;
354
- await this.driver.set(keys[0], allDatabase);
502
+ await this.driver.set(allDatabase);
355
503
  return current;
356
504
  }
357
505
  /**
358
- * Performs an arithmetical addition on a target number in database.
506
+ * Cộng thêm giá trị vào một key dạng number.
359
507
  *
360
- * [!!!] The type of target value must be a number.
508
+ * Nếu key chưa tồn tại, giá trị mặc định sẽ là `0`.
361
509
  *
362
- * @param {AutocompletableString<P>} key The key to access the target in database by.
363
- * @param {number} numberToAdd The number to add to the target number in database.
364
- * @returns {Promise<number>} Addition operation result.
510
+ * @template P Key path trong database.
365
511
  *
366
- * @example
367
- * const additionResult = await database.add("points", 5);
368
- * console.log(additionResult); // -> 10 (5 + 5 = 10)
512
+ * @param key Đường dẫn dữ liệu dạng number.
513
+ * @param numberToAdd Số cần cộng thêm.
369
514
  *
370
- * // Notice that we don't need to assign a value to unexistent properties in database
371
- * // before performing an addition since the initial target value is 0 and will be used
372
- * // as the value of the unexistent property:
373
- * const unexistentAdditionResult = await database.add("somethingElse", 3);
515
+ * @returns Giá trị mới sau khi cộng.
374
516
  *
375
- * console.log(unexistentAdditionResult); // -> 3 (0 + 3 = 3)
376
- * // the property didn't exist in database, that's why 0 is added to 3
377
- *
378
- * // Assuming that the initial database object for this example is:
379
- * // {
380
- * // points: 5
381
- * // }
517
+ * @example
518
+ * ```ts
519
+ * await db.add("economy.users.123.balance", 50);
520
+ * ```
382
521
  */
383
522
  async add(key, numberToAdd) {
384
523
  const targetNumber = await this.get(key) ?? 0;
@@ -394,30 +533,21 @@ var _Database = class _Database {
394
533
  return await this.set(key, targetNumber + numberToAdd);
395
534
  }
396
535
  /**
397
- * Performs an arithmetical subtraction on a target number in database.
536
+ * Trừ giá trị khỏi một key dạng number.
398
537
  *
399
- * [!!!] The type of target value must be a number.
538
+ * Nếu key chưa tồn tại, giá trị mặc định sẽ là `0`.
400
539
  *
401
- * @param {AutocompletableString<P>} key The key to access the target in database by.
402
- * @param {number} numberToSubtract The number to subtract from the target number in database.
403
- * @returns {Promise<number>} Subtraction operation result.
540
+ * @template P Key path trong database.
404
541
  *
405
- * @example
406
- * const subtractionResult = await database.subtract("points", 5)
407
- * console.log(subtractionResult) // -> 5 (10 - 5 = 5)
542
+ * @param key Đường dẫn dữ liệu dạng number.
543
+ * @param numberToSubtract Số cần trừ.
408
544
  *
409
- * // Notice that we don't need to assign a value to unexistent properties in database
410
- * // before performing a subtraction since the initial target value is 0 and will be used
411
- * // as the value of the unexistent property:
412
- * const unexistentSubtractionitionResult = await database.subtract("somethingElse", 3)
545
+ * @returns Giá trị mới sau khi trừ.
413
546
  *
414
- * console.log(unexistentSubtractionitionResult) // -> 3 (0 - 3 = -3)
415
- * // the property didn't exist in database, so 3 is subtracted from 0
416
- *
417
- * // Assuming that the initial database object for this example is:
418
- * // {
419
- * // points: 10
420
- * // }
547
+ * @example
548
+ * ```ts
549
+ * await db.subtract("economy.users.123.balance", 20);
550
+ * ```
421
551
  */
422
552
  async subtract(key, numberToSubtract) {
423
553
  const targetNumber = await this.get(key) ?? 0;
@@ -433,27 +563,31 @@ var _Database = class _Database {
433
563
  return await this.set(key, targetNumber - numberToSubtract);
434
564
  }
435
565
  /**
436
- * Pushes the specified value(s) into the target array in database.
566
+ * Thêm một hoặc nhiều phần tử vào cuối array tại key-path.
437
567
  *
438
- * [!!!] The type of target value must be an array.
439
- * [!!!] get only values ​​not stored in the database.
568
+ * Method này sẽ:
569
+ * - kiểm tra target phải array không
570
+ * - chỉ thêm các giá trị **chưa tồn tại** trong array
440
571
  *
441
- * @param {AutocompletableString<P>} key The key to access the target in database by.
442
- * @param {RestOrArray<ExtractFromArray<ObjectValue<V, P>>>} values
443
- * The value(s) to be pushed into the target array in database.
572
+ * ⚠️ Nếu key không tồn tại hoặc target không phải array
573
+ * thì sẽ ném lỗi.
444
574
  *
445
- * @returns {Promise<Array<ExtractFromArray<ObjectValue<V, P>>>>} Updated target array from database.
575
+ * @template P Key path trong database.
576
+ *
577
+ * @param key Đường dẫn tới array cần thêm phần tử.
578
+ * @param values Một hoặc nhiều giá trị cần thêm.
579
+ *
580
+ * @returns Array sau khi thêm phần tử.
446
581
  *
447
582
  * @example
448
- * console.log(await database.push("members", "Jerry")); // -> ["Tom", "Jerry"]
449
- * // You can also pass in multiple values to push into the target array:
450
- * console.log(await database.push("currencies", "VND")); // -> ["USD", "VND"]
583
+ * ```ts
584
+ * await db.push("users.123.roles", "admin");
585
+ * ```
451
586
  *
452
- * // Assuming that the initial database object for this example is:
453
- * // {
454
- * // members: ["Tom"],
455
- * // currencies: ["USD"]
456
- * // }
587
+ * @example
588
+ * ```ts
589
+ * await db.push("queue.songs", song1, song2);
590
+ * ```
457
591
  */
458
592
  async push(key, ...values) {
459
593
  if (!values.length) {
@@ -483,23 +617,25 @@ var _Database = class _Database {
483
617
  return target[pathParts[pathParts.length - 1]];
484
618
  }
485
619
  /**
486
- * Replaces the specified element in target array with the specified value in the target array in database.
487
- *
488
- * [!!!] The type of target value must be an array.
489
- *
490
- * @param {AutocompletableString<P>} key The key to access the target in database by.
491
- * @param {number} targetArrayElementIndex The index to find the element in target array by.
492
- * @param {V} value The value to be pushed into the target array in database.
493
- * @returns {Promise<Array<ExtractFromArray<ObjectValue<V, P>>>>} Updated target array from database.
494
- *
495
- * @example
496
- * console.log(await database.pull("members", 1, "James")); // -> ["Jerry", "James", "Tom"]
497
- *
498
- * // Assuming that the initial database object for this example is:
499
- * // {
500
- * // members: ["Jerry", "William", "Tom"]
501
- * // }
502
- */
620
+ * Thay thế phần tử trong array theo index.
621
+ *
622
+ * @typeParam P - Path trỏ đến array.
623
+ *
624
+ * @param key - Đường dẫn array.
625
+ * @param targetArrayElementIndex - Index cần thay.
626
+ * @param value - Giá trị mới.
627
+ *
628
+ * @returns Array sau khi thay thế.
629
+ *
630
+ * @throws BlackCatError
631
+ * - INVALID_TYPE nếu index không phải number
632
+ * - REQUIRED_PARAMETER_MISSING nếu thiếu value
633
+ * - INVALID_KEY nếu path không tồn tại
634
+ * - INVALID_TARGET nếu target không phải array
635
+ *
636
+ * @example
637
+ * await db.pull("users", 0, { id: 2 });
638
+ */
503
639
  async pull(key, targetArrayElementIndex, value) {
504
640
  if (!isNumber(targetArrayElementIndex)) {
505
641
  throw new BlackCatError("INVALID_TYPE", "targetArrayElementIndex", "number", typeOf(targetArrayElementIndex));
@@ -539,26 +675,25 @@ var _Database = class _Database {
539
675
  return target[pathParts[pathParts.length - 1]];
540
676
  }
541
677
  /**
542
- * Removes the specified element(s) from the target array in database.
678
+ * Xóa phần tử khỏi array theo index.
543
679
  *
544
- * [!!!] The type of target value must be an array.
680
+ * thể truyền nhiều index hoặc một array index.
545
681
  *
546
- * @param {AutocompletableString<P>} key The key to access the target in database by.
547
- * @param {RestOrArray<ExtractFromArray<number>>} targetArrayElementIndexes
548
- * The index(es) to find the element(s) in target array by.
682
+ * @typeParam P - Path trỏ đến array.
549
683
  *
550
- * @returns {Promise<Array<ExtractFromArray<ObjectValue<V, P>>>>} Updated target array from database.
684
+ * @param key - Đường dẫn array.
685
+ * @param targetArrayElementIndexes - Các index cần xóa.
551
686
  *
552
- * @example
553
- * console.log(await database.pop("members", 1)); // -> ["Jerry", "Tom"]
687
+ * @returns Danh sách phần tử đã bị xóa.
554
688
  *
555
- * console.log(await database.pop("currencies", 1)); // -> ["VND", "Euro"]
689
+ * @throws BlackCatError
690
+ * - INVALID_TARGET nếu target không phải array
691
+ * - REQUIRED_PARAMETER_MISSING nếu thiếu index
692
+ * - ONE_OR_MORE_ARRAY_TYPES_INVALID nếu index không phải number
556
693
  *
557
- * // Assuming that the initial database object for this example is:
558
- * // {
559
- * // members: ["Jerry", "William", "Tom"],
560
- * // currencies: ["VND", "USD", "Euro"]
561
- * // }
694
+ * @example
695
+ * await db.pop("users", 0);
696
+ * await db.pop("numbers", [1, 2, 3]);
562
697
  */
563
698
  async pop(key, ...targetArrayElementIndexes) {
564
699
  const targetArray = await this.get(key) ?? [];
@@ -595,87 +730,52 @@ var _Database = class _Database {
595
730
  return removedElements;
596
731
  }
597
732
  /**
598
- * Determines whether the specified target is an array.
733
+ * Kiểm tra xem giá trị tại key có phải là Array hay không.
599
734
  *
600
- * @param {AutocompletableString<P>} key The key to access the target in database by.
601
- * @returns {Promise<boolean>} Whether the target is an array.
735
+ * @typeParam P - Path của object trong database.
736
+ * @param key - Đường dẫn key cần kiểm tra.
602
737
  *
603
- * @example
604
- * console.log(await databse.isTargetArray("array")); // => true
605
- * console.log(await databse.isTargetArray("notArray")); // => false
738
+ * @returns `true` nếu giá trị là Array, ngược lại `false`.
606
739
  *
607
- * // Assuming that the initial database object for this example is:
608
- * // {
609
- * // array: [],
610
- * // notArray: 123
611
- * // }
740
+ * @example
741
+ * const result = await db.isTargetArray("users");
742
+ * console.log(result);
612
743
  */
613
744
  async isTargetArray(key) {
614
745
  const target = await this.get(key);
615
746
  return Array.isArray(target);
616
747
  }
617
748
  /**
618
- * Determines whether the specified target is a number.
749
+ * Kiểm tra xem giá trị tại key có phải là Number hay không.
619
750
  *
620
- * @param {AutocompletableString<P>} key The key to access the target in database by.
621
- * @returns {Promise<boolean>} Whether the target is a number.
751
+ * @typeParam P - Path của object trong database.
622
752
  *
623
- * @example
624
- * console.log(await database.isTargetNumber("number")); // -> true
625
- * console.log(await database.isTargetNumber("notNumber")); // -> false
753
+ * @param key - Đường dẫn key cần kiểm tra.
626
754
  *
627
- * // Assuming that the initial database object for this example is:
628
- * // {
629
- * // number: 123,
630
- * // notNumber: []
631
- * // }
755
+ * @returns `true` nếu giá trị Number, ngược lại `false`.
756
+ *
757
+ * @example
758
+ * const result = await db.isTargetNumber("stats.score");
759
+ * console.log(result);
632
760
  */
633
761
  async isTargetNumber(key) {
634
762
  const target = await this.get(key);
635
763
  return isNumber(target);
636
764
  }
637
765
  /**
638
- * Returns an array of object keys by specified database key.
766
+ * Lấy danh sách các key của object trong database.
639
767
  *
640
- * If `key` parameter is omitted, then an array of object keys of database root object will be returned.
768
+ * Nếu không truyền `key` trả về các key cấp cao nhất của database.
641
769
  *
642
- * Type parameters:
770
+ * @typeParam P - Path của object.
643
771
  *
644
- * - `TKeys` (`TupleOrArray<string>`, defaults to `K[]`) - The tuple or array of a type of keys to be returned.
772
+ * @param key - Path của object cần lấy danh sách key.
645
773
  *
646
- * @param {P} [key] The key to access the target in database by.
647
- * @returns {Array<ObjectPath<P>>} Database object keys array.
774
+ * @returns Mảng các key tồn tại (không bao gồm `null` hoặc `undefined`).
648
775
  *
649
776
  * @example
650
- * const prop3Keys = await database.keys("prop3");
651
- * console.log(prop3Keys) // -> ["prop4", "prop5"]
652
- *
653
- * const prop5Keys = await database.keys("prop3.prop5");
654
- * console.log(prop5Keys) // -> ["prop6"]
655
- *
656
- * const prop6Keys = await database.keys("prop3.prop5.prop6");
657
- * console.log(prop6Keys)
658
- * // -> [] (empty since the value in `prop6`, 111, is a primitive value and not an actual object)
659
- *
660
- * const databaseKeys = await database.keys();
661
- * // in this example, `key` parameter is omitted - object keys of database object are being returned
662
- *
663
- * console.log(databaseKeys) // -> ["prop1", "prop2", "prop3"]
664
- *
665
- * const unexistentKeys = await database.keys("somethingElse");
666
- * console.log(unexistentKeys) // -> [] (empty since the key `somethingElse` does not exist in database)
667
- *
668
- * // Assuming that the initial database object for this example is:
669
- * // {
670
- * // prop1: 123,
671
- * // prop2: 456,
672
- * // prop3: {
673
- * // prop4: 789,
674
- * // prop5: {
675
- * // prop6: 111
676
- * // }
677
- * // }
678
- * // }
777
+ * const rootKeys = await db.keys();
778
+ * const userKeys = await db.keys("user");
679
779
  */
680
780
  async keys(key) {
681
781
  if (!key) return TypedObject.keys(await this.all());
@@ -683,51 +783,33 @@ var _Database = class _Database {
683
783
  return TypedObject.keys(data).filter((key2) => data[key2] !== void 0 && data[key2] !== null);
684
784
  }
685
785
  /**
686
- * Determines the number of keys in the root of the database.
687
- * @type {Promise<number>} amount of data.
786
+ * Lấy số lượng key cấp cao nhất trong database.
787
+ *
788
+ * @returns Tổng số key ở root level.
789
+ *
790
+ * @example
791
+ * const count = await db.size();
688
792
  */
689
793
  async size() {
690
794
  const keys = await this.keys();
691
795
  return keys.length;
692
796
  }
693
797
  /**
694
- * Returns an array of object values by specified database key.
695
- *
696
- * If `key` parameter is omitted, then an array of object values of database root object will be returned.
697
- *
698
- * @param {P} [key] The key to access the target in database by.
699
- * @returns {Array<ObjectValue<V, P>>} Database object values array.
700
- *
701
- * @example
702
- * const prop3Values = await database.values("prop3");
703
- * console.log(prop3Values); // -> [789, { prop6: 111 }]
798
+ * Lấy danh sách các giá trị từ database.
704
799
  *
705
- * const prop5Values = await database.values("prop3.prop5");
706
- * console.log(prop5Values); // -> []
800
+ * Nếu không truyền `key` → trả về toàn bộ values ở root level.
801
+ * Nếu truyền `key` → trả về values của object tại path đó.
707
802
  *
708
- * const prop6Values = await database.values("prop3.prop5.prop6");
709
- * console.log(prop6Values);
710
- * // -> [] (empty since the value in `prop6`, 111, is a primitive value and not an actual object)
803
+ * @typeParam P - Path của object trong database.
711
804
  *
712
- * const databaseValues = await database.values();
713
- * // in this example, `key` parameter is omitted - object values of database object are being returned
805
+ * @param key - Đường dẫn object cần lấy values.
714
806
  *
715
- * console.log(databaseValues); // -> [123, 456, { prop4: 789, prop5: { prop6: 111 } }]
807
+ * @returns Mảng các giá trị.
716
808
  *
717
- * const unexistentValues = await database.values("somethingElse");
718
- * console.log(unexistentValues); // -> [] (empty since the key `somethingElse` does not exist in database)
809
+ * @example
810
+ * const allValues = await db.values();
719
811
  *
720
- * // Assuming that the initial database object for this example is:
721
- * // {
722
- * // prop1: 123,
723
- * // prop2: 456,
724
- * // prop3: {
725
- * // prop4: 789,
726
- * // prop5: {
727
- * // prop6: 111
728
- * // }
729
- * // }
730
- * // }
812
+ * const userValues = await db.values("users");
731
813
  */
732
814
  async values(key) {
733
815
  if (!key) return TypedObject.values(await this.all());
@@ -735,160 +817,125 @@ var _Database = class _Database {
735
817
  return TypedObject.values(data);
736
818
  }
737
819
  /**
738
- * This method works the same way as `Array.find()`.
820
+ * Lấy ngẫu nhiên một phần tử từ array tại path được chỉ định.
821
+ *
822
+ * @typeParam P - Path trỏ đến array trong database.
823
+ *
824
+ * @param key - Đường dẫn đến array.
825
+ *
826
+ * @returns Một phần tử ngẫu nhiên trong array hoặc `null` nếu array rỗng.
827
+ *
828
+ * @throws BlackCatError
829
+ * - INVALID_TARGET nếu giá trị tại key không phải array
830
+ *
831
+ * @example
832
+ * const randomUser = await db.random("users");
833
+ */
834
+ async random(key) {
835
+ const array = await this.get(key);
836
+ if (!Array.isArray(array)) {
837
+ throw new BlackCatError("INVALID_TARGET", "array", typeOf(array));
838
+ }
839
+ return array[Math.floor(Math.random() * array.length)] ?? null;
840
+ }
841
+ /**
842
+ * Tìm phần tử đầu tiên thỏa điều kiện.
843
+ *
844
+ * Hoạt động tương tự `Array.prototype.find`.
739
845
  *
740
- * Iterates over root database values, finds the element in database values array
741
- * by specified condition in the callback function and returns the result.
846
+ * @param queryFunction - Hàm kiểm tra điều kiện.
742
847
  *
743
- * @param {QueryFunction<V>} queryFunction
744
- * A function that accepts up to three arguments.
745
- * The `find` method calls the `queryFunction` once for each element in database object values array.
848
+ * @returns Phần tử đầu tiên thỏa điều kiện hoặc `null` nếu không tìm thấy.
746
849
  *
747
- * @returns {Promise<Maybe<V>>} The search
850
+ * @example
851
+ * const user = await db.find(u => u.id === 1);
748
852
  */
749
853
  async find(queryFunction) {
750
854
  const values = await this.values();
751
855
  return values.find(queryFunction) ?? null;
752
856
  }
753
857
  /**
754
- * This method works the same way as `Array.map()`.
858
+ * Biến đổi tất cả giá trị trong database thành một mảng mới.
859
+ *
860
+ * Hoạt động giống `Array.prototype.map`.
755
861
  *
756
- * Calls a defined callback function on each element of an array,
757
- * and returns an array that contains the results.
862
+ * @typeParam TReturnType - Kiểu dữ liệu của phần tử trả về.
758
863
  *
759
- * @param {QueryFunction<V, TReturnType>} queryFunction
760
- * A function that accepts up to three arguments.
761
- * The `map` method calls the `queryFunction` once for each element in database object values array.
864
+ * @param queryFunction - Hàm transform từng phần tử.
762
865
  *
763
- * @returns {Promise<TReturnType[]>}
866
+ * @returns Mảng kết quả sau khi transform.
867
+ *
868
+ * @example
869
+ * const names = await db.map(user => user.name);
764
870
  */
765
871
  async map(queryFunction) {
766
872
  const values = await this.values();
767
873
  return values.map(queryFunction);
768
874
  }
769
875
  /**
770
- * This method works the same way as `Array.findIndex()`.
876
+ * Tìm index của phần tử đầu tiên thỏa điều kiện.
877
+ *
878
+ * Hoạt động giống `Array.prototype.findIndex`.
771
879
  *
772
- * Iterates over root database values, finds the index of the element in database values array
773
- * by specified condition in the callback function and returns the result.
880
+ * @param queryFunction - Hàm kiểm tra điều kiện.
774
881
  *
775
- * @param {QueryFunction<V>} queryFunction
776
- * A function that accepts up to three arguments.
777
- * The `findIndex` method calls the `queryFunction` once for each element in database object values array.
882
+ * @returns Index của phần tử hoặc `-1` nếu không tìm thấy.
778
883
  *
779
- * @returns {Promise<number>}
884
+ * @example
885
+ * const index = await db.findIndex(user => user.id === 1);
780
886
  */
781
887
  async findIndex(queryFunction) {
782
888
  const values = await this.values();
783
889
  return values.findIndex(queryFunction);
784
890
  }
785
891
  /**
786
- * This method works the same way as `Array.filter()`.
892
+ * Lọc các phần tử thỏa điều kiện.
893
+ *
894
+ * Hoạt động giống `Array.prototype.filter`.
787
895
  *
788
- * Iterates over root database values, finds all the element that match the
789
- * specified condition in the callback function and returns the result.
896
+ * @param queryFunction - Hàm kiểm tra điều kiện.
790
897
  *
791
- * @param {QueryFunction<V>} queryFunction
792
- * A function that accepts up to three arguments.
793
- * The `filter` method calls the `queryFunction` once for each element in database object values array.
898
+ * @returns Mảng các phần tử thỏa điều kiện.
794
899
  *
795
- * @returns {Promise<V[]>}
900
+ * @example
901
+ * const admins = await db.filter(user => user.role === "admin");
796
902
  */
797
903
  async filter(queryFunction) {
798
904
  const values = await this.values();
799
905
  return values.filter(queryFunction);
800
906
  }
801
907
  /**
802
- * This method works the same way as `Array.some()`.
908
+ * Kiểm tra ít nhất một phần tử thỏa điều kiện hay không.
909
+ *
910
+ * Hoạt động giống `Array.prototype.some`.
803
911
  *
804
- * Iterates over root database values and checks if the
805
- * specified condition in the callback function returns `true`
806
- * for **any** of the elements of the database object values array.
912
+ * @param queryFunction - Hàm kiểm tra điều kiện.
807
913
  *
808
- * @param {QueryFunction<V>} queryFunction
809
- * A function that accepts up to three arguments.
810
- * The `some` method calls the `queryFunction` once for each element in database object values array.
914
+ * @returns `true` nếu tồn tại phần tử thỏa điều kiện.
811
915
  *
812
- * @returns {Promise<boolean>}
916
+ * @example
917
+ * const hasAdmin = await db.some(user => user.role === "admin");
813
918
  */
814
919
  async some(queryFunction) {
815
920
  const values = await this.values();
816
921
  return values.some(queryFunction);
817
922
  }
818
923
  /**
819
- * This method works the same way as `Array.every()`.
924
+ * Kiểm tra tất cả phần tử thỏa điều kiện hay không.
820
925
  *
821
- * Iterates over root database values and checks if the
822
- * specified condition in the callback function returns `true`
823
- * for **all** of the elements of the database object values array.
926
+ * Hoạt động giống `Array.prototype.every`.
824
927
  *
825
- * @param {QueryFunction<V>} queryFunction
826
- * A function that accepts up to three arguments.
827
- * The `every` method calls the `queryFunction` once for each element in database object values array.
928
+ * @param queryFunction - Hàm kiểm tra điều kiện.
828
929
  *
829
- * @returns {Promise<boolean>}
930
+ * @returns `true` nếu tất cả phần tử đều thỏa điều kiện.
931
+ *
932
+ * @example
933
+ * const allActive = await db.every(user => user.active === true);
830
934
  */
831
935
  async every(queryFunction) {
832
936
  const values = await this.values();
833
937
  return values.every(queryFunction);
834
938
  }
835
- /**
836
- * Picks a random element of array in database and returns the picked array element.
837
- *
838
- * [!!!] The type of target value must be an array.
839
- *
840
- * @param {AutocompletableString<P>} key The key to access the target in database by.
841
- * @returns {Promise<Maybe<ObjectValue<V, P>>>} The randomly picked element in the database array.
842
- *
843
- * @example
844
- * const array = await database.get("array"); // assuming that the array is ['example1', 'example2', 'example3']
845
- * console.log(array); // -> ['example1', 'example2', 'example3']
846
- *
847
- * const randomArrayElement = await database.random("exampleArray");
848
- * console.log(randomArrayElement); // -> randomly picked array element: either 'example1', 'example2', or 'example3'
849
- */
850
- async random(key) {
851
- const array = await this.get(key);
852
- if (!Array.isArray(array)) {
853
- throw new BlackCatError("INVALID_TARGET", "array", typeOf(array));
854
- }
855
- return array[Math.floor(Math.random() * array.length)] ?? null;
856
- }
857
- /**
858
- * Deletes the data from database by key.
859
- * @param {AutocompletableString<P>} key The key to access the target in database by.
860
- * @returns {Promise<boolean>} Whether the deletion was successful.
861
- */
862
- async delete(key) {
863
- if (typeof key !== "string") {
864
- throw new BlackCatError("INVALID_TYPE", "key", "string", typeof key);
865
- }
866
- ;
867
- const allDatabase = await this.all();
868
- const keys = key.split(".");
869
- const lastKey = keys.pop();
870
- let currentObj = allDatabase;
871
- for (const k of keys) {
872
- if (!isObject(currentObj[k])) {
873
- return false;
874
- }
875
- currentObj = currentObj[k];
876
- }
877
- if (!(lastKey in currentObj)) return false;
878
- delete currentObj[lastKey];
879
- await this.driver.delete(allDatabase);
880
- return true;
881
- }
882
- /**
883
- * Deletes everything from the database.
884
- *
885
- * - This method is an alias for {@link QuickMongo.clear()} method.
886
- * @returns {Promise<boolean>} `true` if cleared successfully, `false` otherwise.
887
- */
888
- async deleteAll() {
889
- await this.driver.delete();
890
- return true;
891
- }
892
939
  };
893
940
  __name(_Database, "Database");
894
941
  var Database = _Database;
@@ -897,99 +944,338 @@ var Database = _Database;
897
944
  var import_fs = require("fs");
898
945
  var _JSONDriver = class _JSONDriver {
899
946
  /**
900
- * JSONDriver class.
901
- * @param options.filePath Json database file path.
902
- * @param options.minifyJSON Minifies the JSON content in database file to save some space.
947
+ * Khởi tạo một instance mới của {@link JSONDriver}.
948
+ *
949
+ * @param options - Cấu hình driver
950
+ *
951
+ * @param options.filePath
952
+ * Đường dẫn tới file JSON dùng làm database.
953
+ *
954
+ * @param options.minifyJSON
955
+ * Nếu `true`, nội dung JSON sẽ được minify khi ghi ra file để giảm dung lượng.
956
+ *
957
+ * @example
958
+ * ```ts
959
+ * const database = new Database({
960
+ * driver: db = new JSONDriver({
961
+ * filePath: "./database.json"
962
+ * })
963
+ * });
964
+ * ```
903
965
  */
904
966
  constructor(options) {
905
967
  /**
906
- * JSON database file path.
907
- * @type {string}
968
+ * Đường dẫn tới file database JSON.
908
969
  */
909
970
  __publicField(this, "filePath");
910
971
  /**
911
- * Minifies the JSON content in database file to save some space.
912
- * @type {boolean}
972
+ * Cho biết có minify JSON khi ghi file hay không.
913
973
  */
914
974
  __publicField(this, "minifyJSON");
915
975
  this.filePath = options.filePath || "database.json";
916
976
  this.minifyJSON = options.minifyJSON || false;
917
977
  }
918
978
  /**
919
- * Returns all data from JSON database.
920
- *
921
- * @returns {Promise<any>} All data from JSON database.
922
- *
923
- * @template V The type of data being returned.
979
+ * Đảm bảo file database tồn tại.
980
+ * Nếu file chưa tồn tại sẽ tự động tạo file `{}`.
981
+ */
982
+ async ensureFile() {
983
+ try {
984
+ await import_fs.promises.access(this.filePath);
985
+ } catch {
986
+ await import_fs.promises.writeFile(this.filePath, "{}");
987
+ }
988
+ }
989
+ /**
990
+ * Đọc toàn bộ dữ liệu từ file database JSON.
991
+ *
992
+ * Nếu file không tồn tại hoặc lỗi parse,
993
+ * method sẽ trả về object rỗng.
994
+ *
995
+ * @template V Kiểu dữ liệu database.
996
+ * @returns Promise chứa toàn bộ dữ liệu database.
924
997
  */
925
998
  async all() {
999
+ await this.ensureFile();
926
1000
  return import_fs.promises.readFile(this.filePath, "utf-8").then((content) => JSON.parse(content)).catch((error) => {
927
- console.error(`Failed to load database file: ${this.filePath}`, error);
1001
+ console.error(`Kh\xF4ng th\u1EC3 \u0111\u1ECDc file database: ${this.filePath}`, error);
928
1002
  return {};
929
1003
  });
930
1004
  }
931
1005
  /**
932
- * Parses the key and fetches the value from JSON database.
1006
+ * Ghi toàn bộ dữ liệu database xuống file JSON.
933
1007
  *
934
- * Type parameters:
1008
+ * Method này **không xử lý key path**.
1009
+ * Logic cập nhật dữ liệu sẽ được xử lý ở class `Database`
1010
+ * trước khi truyền object hoàn chỉnh vào đây.
1011
+ *
1012
+ * @param data Toàn bộ dữ liệu database sau khi đã được cập nhật.
935
1013
  *
936
- * - `V` - The type of data being returned.
1014
+ * @template R Kiểu dữ liệu database.
1015
+ * @returns Promise chứa dữ liệu đã ghi.
1016
+ */
1017
+ async set(data) {
1018
+ await this.ensureFile();
1019
+ await import_fs.promises.writeFile(this.filePath, JSON.stringify(data, null, this.minifyJSON ? void 0 : " "));
1020
+ return data;
1021
+ }
1022
+ /**
1023
+ * Xóa toàn bộ database.
937
1024
  *
938
- * @param {string} key The key in JSON database.
939
- * @returns {Promise<V>} The data from JSON database.
1025
+ * Method này chỉ reset file JSON về `{}`.
940
1026
  *
941
- * @template V The type of data being returned.
1027
+ * @returns `true` nếu reset thành công.
942
1028
  */
943
- async get(key) {
944
- const data = await this.all();
945
- const keys = key.split(".");
946
- let result = data;
947
- for (const k of keys) {
948
- if (result === null || typeof result !== "object") return null;
949
- result = result[k];
950
- }
951
- return result;
1029
+ async delete() {
1030
+ await this.ensureFile();
1031
+ await import_fs.promises.writeFile(this.filePath, "{}");
1032
+ return true;
952
1033
  }
1034
+ };
1035
+ __name(_JSONDriver, "JSONDriver");
1036
+ var JSONDriver = _JSONDriver;
1037
+
1038
+ // src/drivers/MemoryDriver.ts
1039
+ var _MemoryDriver = class _MemoryDriver {
953
1040
  /**
954
- * Parses the key and sets the value in JSON database.
1041
+ * Khởi tạo MemoryDriver.
1042
+ *
1043
+ * @param initialData Dữ liệu khởi tạo ban đầu.
1044
+ * * @example
1045
+ * ```ts
1046
+ * const database = new Database({
1047
+ * driver: new MemoryDriver({
1048
+ * users: {},
1049
+ * guilds: {},
1050
+ * settings: {
1051
+ * prefix: "!"
1052
+ * }
1053
+ * })
1054
+ * });
1055
+ * ```
1056
+ *
1057
+ * hoặc
1058
+ *
1059
+ * ```ts
1060
+ * const database = new Database({
1061
+ * driver: new MemoryDriver()
1062
+ * });
1063
+ * ```
1064
+ */
1065
+ constructor(initialData = {}) {
1066
+ /**
1067
+ * Object chứa toàn bộ dữ liệu database trong RAM.
1068
+ */
1069
+ __publicField(this, "store");
1070
+ this.store = initialData;
1071
+ }
1072
+ /**
1073
+ * Trả về toàn bộ dữ liệu database.
955
1074
  *
956
- * Type parameters:
1075
+ * @template T Kiểu dữ liệu database.
1076
+ */
1077
+ async all() {
1078
+ return this.store;
1079
+ }
1080
+ /**
1081
+ * Ghi toàn bộ database vào memory.
1082
+ *
1083
+ * ⚠️ Method này **không xử lý key-path**.
1084
+ * Dữ liệu đã được xử lý trước bởi `Database`.
1085
+ *
1086
+ * @param data Toàn bộ database object
1087
+ */
1088
+ async set(data) {
1089
+ this.store = data;
1090
+ return data;
1091
+ }
1092
+ /**
1093
+ * Xóa toàn bộ dữ liệu database trong memory.
1094
+ */
1095
+ async delete() {
1096
+ this.store = {};
1097
+ return true;
1098
+ }
1099
+ };
1100
+ __name(_MemoryDriver, "MemoryDriver");
1101
+ var MemoryDriver = _MemoryDriver;
1102
+
1103
+ // src/drivers/SQLiteDriver.ts
1104
+ var import_better_sqlite3 = __toESM(require("better-sqlite3"));
1105
+ var _SQLiteDriver = class _SQLiteDriver {
1106
+ /**
1107
+ * Khởi tạo SQLiteDriver.
1108
+ *
1109
+ * @param filePath Đường dẫn file SQLite
1110
+ * @param table Tên table lưu JSON database
1111
+ * @example
1112
+ * ```ts
1113
+ * const database = new Database({
1114
+ * driver: new SQLiteDriver({
1115
+ * filePath: "database.sqlite",
1116
+ * table: "json_store"
1117
+ * })
1118
+ * })
1119
+ * ```
1120
+ */
1121
+ constructor(options = {}) {
1122
+ /**
1123
+ * SQLite database instance.
1124
+ */
1125
+ __publicField(this, "db");
1126
+ /**
1127
+ * Tên table lưu trữ dữ liệu JSON.
1128
+ */
1129
+ __publicField(this, "table");
1130
+ this.db = new import_better_sqlite3.default(options.filePath ?? "database.sqlite");
1131
+ this.table = options.table ?? "json_store";
1132
+ this.db.prepare(`CREATE TABLE IF NOT EXISTS ${this.table} (id INTEGER PRIMARY KEY, data TEXT)`).run();
1133
+ const row = this.db.prepare(`SELECT * FROM ${this.table} WHERE id = 1`).get();
1134
+ if (!row) {
1135
+ this.db.prepare(`INSERT INTO ${this.table} (id, data) VALUES (1, '{}')`).run();
1136
+ }
1137
+ }
1138
+ /**
1139
+ * Lấy toàn bộ dữ liệu database từ SQLite.
957
1140
  *
958
- * - `V` - The type of data being set.
959
- * - `R` - The type of data being returned.
1141
+ * @template T Kiểu dữ liệu database.
1142
+ */
1143
+ async all() {
1144
+ const row = this.db.prepare(`SELECT data FROM ${this.table} WHERE id = 1`).get();
1145
+ return JSON.parse(row.data);
1146
+ }
1147
+ /**
1148
+ * Ghi toàn bộ database vào SQLite.
960
1149
  *
961
- * @param {string} key The key in JSON database.
962
- * @returns {Promise<R>} The data from JSON database.
1150
+ * ⚠️ Method này **không xử key-path**.
1151
+ * `Database` đã cập nhật object trước khi truyền vào đây.
963
1152
  *
964
- * @template V The type of data being set.
965
- * @template R The type of data being returned.
1153
+ * @param data Toàn bộ database object
966
1154
  */
967
- async set(key, value) {
968
- const data = await this.all();
969
- await import_fs.promises.writeFile(this.filePath, JSON.stringify(value, null, this.minifyJSON ? void 0 : " "));
1155
+ async set(data) {
1156
+ this.db.prepare(`UPDATE ${this.table} SET data = ? WHERE id = 1`).run(JSON.stringify(data));
970
1157
  return data;
971
1158
  }
972
1159
  /**
973
- * Parses the key and deletes it from JSON database. If no key is provided, clears the database.
974
- * @param {V} key The key in JSON database.
975
- * @returns {Promise<boolean>} `true` if deleted successfully.
1160
+ * Reset toàn bộ database.
976
1161
  */
977
- async delete(key) {
978
- if (key === void 0) {
979
- await import_fs.promises.writeFile(this.filePath, "{}");
980
- return true;
981
- } else {
982
- await import_fs.promises.writeFile(this.filePath, JSON.stringify(key, null, this.minifyJSON ? void 0 : " "));
1162
+ async delete() {
1163
+ this.db.prepare(`UPDATE ${this.table} SET data = '{}' WHERE id = 1`).run();
1164
+ return true;
1165
+ }
1166
+ };
1167
+ __name(_SQLiteDriver, "SQLiteDriver");
1168
+ var SQLiteDriver = _SQLiteDriver;
1169
+
1170
+ // src/drivers/MongoDriver.ts
1171
+ var import_mongodb = require("mongodb");
1172
+ var _MongoDriver = class _MongoDriver {
1173
+ /**
1174
+ * Khởi tạo MongoDriver.
1175
+ *
1176
+ * @param options Cấu hình MongoDB driver.
1177
+ *
1178
+ * @example
1179
+ * ```ts
1180
+ * const database = new Database({
1181
+ * driver: new MongoDriver({
1182
+ * mongourl: "mongodb://localhost:27017",
1183
+ * databaseName: "mydb",
1184
+ * collectionName: "store"
1185
+ * })
1186
+ * });
1187
+ */
1188
+ constructor(options = {}) {
1189
+ /**
1190
+ * MongoDB client instance.
1191
+ */
1192
+ __publicField(this, "client");
1193
+ /**
1194
+ * MongoDB database instance.
1195
+ */
1196
+ __publicField(this, "db");
1197
+ /**
1198
+ * Collection lưu dữ liệu JSON.
1199
+ */
1200
+ __publicField(this, "collection");
1201
+ /**
1202
+ * Tên database MongoDB.
1203
+ */
1204
+ __publicField(this, "databaseName");
1205
+ /**
1206
+ * Tên collection MongoDB.
1207
+ */
1208
+ __publicField(this, "collectionName");
1209
+ const {
1210
+ mongourl = "mongodb://localhost:27017",
1211
+ databaseName = "database",
1212
+ collectionName = "json_store"
1213
+ } = options;
1214
+ this.client = new import_mongodb.MongoClient(mongourl);
1215
+ this.databaseName = databaseName;
1216
+ this.collectionName = collectionName;
1217
+ }
1218
+ /**
1219
+ * Thiết lập kết nối MongoDB nếu chưa kết nối.
1220
+ */
1221
+ async connect() {
1222
+ if (!this.db) {
1223
+ await this.client.connect();
1224
+ this.db = this.client.db(this.databaseName);
1225
+ this.collection = this.db.collection(this.collectionName);
1226
+ const doc = await this.collection.findOne({ _id: "database" });
1227
+ if (!doc) {
1228
+ await this.collection.insertOne({
1229
+ _id: "database",
1230
+ data: {}
1231
+ });
1232
+ }
983
1233
  }
984
- ;
1234
+ }
1235
+ /**
1236
+ * Lấy toàn bộ dữ liệu database từ MongoDB.
1237
+ */
1238
+ async all() {
1239
+ await this.connect();
1240
+ const doc = await this.collection.findOne({ _id: "database" });
1241
+ return doc?.data ?? {};
1242
+ }
1243
+ /**
1244
+ * Ghi toàn bộ database vào MongoDB.
1245
+ *
1246
+ * ⚠️ Method này **không xử lý key-path**.
1247
+ * Object database đã được xử lý bởi class `Database`.
1248
+ *
1249
+ * @param data Toàn bộ object database
1250
+ */
1251
+ async set(data) {
1252
+ await this.connect();
1253
+ await this.collection.updateOne(
1254
+ { _id: "database" },
1255
+ { $set: { data } }
1256
+ );
1257
+ return data;
1258
+ }
1259
+ /**
1260
+ * Reset toàn bộ database về object rỗng.
1261
+ */
1262
+ async delete() {
1263
+ await this.connect();
1264
+ await this.collection.updateOne(
1265
+ { _id: "database" },
1266
+ { $set: { data: {} } }
1267
+ );
985
1268
  return true;
986
1269
  }
987
1270
  };
988
- __name(_JSONDriver, "JSONDriver");
989
- var JSONDriver = _JSONDriver;
1271
+ __name(_MongoDriver, "MongoDriver");
1272
+ var MongoDriver = _MongoDriver;
990
1273
  // Annotate the CommonJS export names for ESM import in node:
991
1274
  0 && (module.exports = {
992
1275
  Database,
993
- JSONDriver
1276
+ JSONDriver,
1277
+ MemoryDriver,
1278
+ MongoDriver,
1279
+ SQLiteDriver
994
1280
  });
995
1281
  //# sourceMappingURL=index.js.map