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/dist/index.d.ts CHANGED
@@ -1,3 +1,5 @@
1
+ import { MongoClient, Db, Collection } from 'mongodb';
2
+
1
3
  /**
2
4
  * Interface định nghĩa contract cho các storage driver
3
5
  * được sử dụng bởi class `Database`.
@@ -111,7 +113,32 @@ interface DatabaseConfiguration {
111
113
  */
112
114
  type Maybe<T> = Exclude<T | null, undefined>;
113
115
  /**
116
+ * Utility type dùng để trích xuất kiểu phần tử bên trong một mảng.
117
+ * @hidden
118
+ *
119
+ * Nếu `T` là một mảng (`U[]`) thì kiểu trả về sẽ là `U` (kiểu phần tử).
120
+ * Nếu `T` không phải là mảng thì kiểu trả về chính là `T`.
121
+ *
122
+ * Thường được sử dụng trong các generic type để làm việc
123
+ * với kiểu dữ liệu của phần tử trong mảng một cách an toàn.
124
+ *
125
+ * @typeParam T - Kiểu dữ liệu đầu vào, có thể là mảng hoặc bất kỳ kiểu nào.
114
126
  *
127
+ * @example
128
+ * type A = ArrayElement<string[]>;
129
+ * // Kết quả: string
130
+ *
131
+ * @example
132
+ * type B = ArrayElement<number[]>;
133
+ * // Kết quả: number
134
+ *
135
+ * @example
136
+ * type C = ArrayElement<string>;
137
+ * // Kết quả: string
138
+ *
139
+ * @example
140
+ * type D = ArrayElement<(number | string)[]>;
141
+ * // Kết quả: number | string
115
142
  */
116
143
  type ArrayElement<T> = T extends (infer U)[] ? U : T;
117
144
  /**
@@ -308,26 +335,6 @@ type IsAny<T> = 0 extends (1 & T) ? true : false;
308
335
  * const c: Status = "custom"; // vẫn hợp lệ
309
336
  */
310
337
  type AutocompletableString<S extends string> = S | (string & {});
311
- /**
312
- * Trích xuất **key đầu tiên** từ một object path dạng chuỗi.
313
- * @hidden
314
- *
315
- * Ví dụ với path `"member.user.id"` thì key đầu tiên sẽ là `"member"`.
316
- *
317
- * Type này thường được dùng để xác định **object cấp cao nhất**
318
- * khi làm việc với các path dạng `dot notation`.
319
- *
320
- * @typeParam TKey - Object path cần trích xuất key đầu tiên.
321
- *
322
- * @example
323
- * type A = FirstObjectKey<"user.profile.name">;
324
- * // Kết quả: "user"
325
- *
326
- * @example
327
- * type B = FirstObjectKey<"settings">;
328
- * // Kết quả: "settings"
329
- */
330
- type FirstObjectKey<TKey extends ObjectPath<string, any>> = TKey extends `${infer Key}.${infer _Rest}` ? Key : TKey extends string ? TKey : never;
331
338
  /**
332
339
  * Đại diện cho **đường dẫn (path)** tới một thuộc tính trong object,
333
340
  * hỗ trợ truy cập các property lồng nhau bằng `dot notation`.
@@ -369,7 +376,7 @@ type FirstObjectKey<TKey extends ObjectPath<string, any>> = TKey extends `${infe
369
376
  * // "user.profile"
370
377
  * // "user.profile.name"
371
378
  */
372
- type ObjectPath<T, TKey extends keyof T = keyof T> = IsAny<T> extends true ? string : T extends string | number | boolean | symbol ? string : T extends Array<any> ? TKey & string : TKey extends string ? T[TKey] extends Array<any> ? TKey : T[TKey] extends Record<string, any> ? `${TKey}` | `${TKey}.${ObjectPath<T[TKey]>}` : TKey : never;
379
+ type ObjectPath<T, TKey extends keyof T = keyof T> = IsAny<T> extends true ? string : T extends string | number | boolean | symbol ? string : T extends Array<any> ? TKey & string : TKey extends string ? NonNullable<T[TKey]> extends Array<any> ? TKey : NonNullable<T[TKey]> extends Record<string, any> ? `${TKey}` | `${TKey}.${ObjectPath<NonNullable<T[TKey]>>}` : TKey : never;
373
380
  /**
374
381
  * Trích xuất kiểu dữ liệu của giá trị tại một object path.
375
382
  * @hidden
@@ -399,7 +406,7 @@ type ObjectPath<T, TKey extends keyof T = keyof T> = IsAny<T> extends true ? str
399
406
  * type C = ObjectValue<User, "profile">;
400
407
  * // Kết quả: { name: string; age: number }
401
408
  */
402
- type ObjectValue<T, P extends ObjectPath<T> | AutocompletableString<ObjectPath<T>>> = T extends AutocompletableString<P> | string | number | boolean | symbol ? T : P extends `${infer Key}.${infer Rest}` ? Key extends keyof T ? Rest extends ObjectPath<T[Key]> ? ObjectValue<T[Key], Rest> : null : never : P extends keyof T ? T[P] : T;
409
+ type ObjectValue<T, P extends ObjectPath<T> | AutocompletableString<ObjectPath<T>>> = T extends string | number | boolean | bigint | symbol | null | undefined | Date | Function ? T : T extends (infer U)[] ? ObjectValue<U, P>[] : P extends `${infer Key}.${infer Rest}` ? Key extends keyof T ? ObjectValue<T[Key], Rest> : never : P extends keyof T ? T[P] : never;
403
410
 
404
411
  /**
405
412
  * Class Database cung cấp API thao tác dữ liệu dạng key-path
@@ -479,7 +486,7 @@ declare class Database<V = any> {
479
486
  * console.log(data.users);
480
487
  * ```
481
488
  */
482
- all<T extends Record<string, any> = Record<string, any>>(): Promise<T>;
489
+ all(): Promise<V>;
483
490
  /**
484
491
  * Lấy giá trị từ database theo key-path.
485
492
  *
@@ -508,7 +515,7 @@ declare class Database<V = any> {
508
515
  * const all = await db.get();
509
516
  * ```
510
517
  */
511
- get<P extends AutocompletableString<ObjectPath<V>>>(key?: AutocompletableString<P>): Promise<Maybe<ObjectValue<V, P>> | V>;
518
+ get<P extends AutocompletableString<ObjectPath<V>>>(key?: AutocompletableString<P>): Promise<Maybe<ObjectValue<V, P>>>;
512
519
  /**
513
520
  * Tìm và trả về một bản ghi đầu tiên khớp với điều kiện trong database.
514
521
  *
@@ -545,7 +552,7 @@ declare class Database<V = any> {
545
552
  * });
546
553
  * ```
547
554
  */
548
- findOne<P extends AutocompletableString<ObjectPath<V>>>(key?: AutocompletableString<P>, query?: Partial<ArrayElement<ObjectValue<V, P>>>): Promise<Maybe<ObjectValue<V, P>> | V>;
555
+ findOne<P extends AutocompletableString<ObjectPath<V>>>(key?: AutocompletableString<P>, query?: Partial<ArrayElement<ObjectValue<V, P>>>): Promise<Maybe<ObjectValue<V, P>>>;
549
556
  /**
550
557
  * Kiểm tra một key-path có tồn tại trong database hay không.
551
558
  *
@@ -574,7 +581,7 @@ declare class Database<V = any> {
574
581
  * @param {AutocompletableString<P>} key Đường dẫn dữ liệu cần gán giá trị.
575
582
  * @param {ObjectValue<V, P>} value Giá trị mới.
576
583
  *
577
- * @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.
584
+ * @returns {void} Giá trị vừa được set hoặc object root nếu value là object.
578
585
  *
579
586
  * @example
580
587
  * ```ts
@@ -586,7 +593,7 @@ declare class Database<V = any> {
586
593
  * await db.set("config.prefix", "!");
587
594
  * ```
588
595
  */
589
- set<P extends AutocompletableString<ObjectPath<V>>>(key: AutocompletableString<P>, value: ObjectValue<V, P>): Promise<If<IsObject<V>, ObjectValue<V, FirstObjectKey<P>>, V>>;
596
+ set<P extends AutocompletableString<ObjectPath<V>>>(key: AutocompletableString<P>, value: ObjectValue<V, P>): Promise<void>;
590
597
  /**
591
598
  * Xóa một key khỏi database.
592
599
  *
@@ -715,7 +722,7 @@ declare class Database<V = any> {
715
722
  * - `REQUIRED_PARAMETER_MISSING` nếu key không được cung cấp
716
723
  * - `INVALID_TYPE` nếu key không phải string
717
724
  */
718
- update<P extends AutocompletableString<ObjectPath<V>>>(key: AutocompletableString<P>, value: ObjectValue<V, P>): Promise<If<IsObject<V>, ObjectValue<V, FirstObjectKey<P>>, V>>;
725
+ update<P extends AutocompletableString<ObjectPath<V>>>(key: AutocompletableString<P>, value: ObjectValue<V, P>): Promise<If<IsObject<V>, ObjectValue<V, P>>>;
719
726
  /**
720
727
  * Cộng thêm giá trị vào một key dạng number.
721
728
  *
@@ -1310,6 +1317,53 @@ declare class SQLiteDriver implements DatabaseDriver {
1310
1317
  delete(): Promise<boolean>;
1311
1318
  }
1312
1319
 
1320
+ /**
1321
+ * Context được truyền vào callback `onLoad` của MongoDriver.
1322
+ * @hidden
1323
+ */
1324
+ interface MongoDriverOnLoadContext {
1325
+ /**
1326
+ * Instance MongoClient đã kết nối.
1327
+ */
1328
+ client: MongoClient;
1329
+ /**
1330
+ * Database hiện tại.
1331
+ */
1332
+ db: Db;
1333
+ /**
1334
+ * Collection đang được sử dụng.
1335
+ */
1336
+ collection: Collection<DatabaseDocument>;
1337
+ /**
1338
+ * Tên database.
1339
+ */
1340
+ databaseName: string;
1341
+ /**
1342
+ * Tên collection.
1343
+ */
1344
+ collectionName: string;
1345
+ }
1346
+ /**
1347
+ * Context được truyền vào callback `onError` của MongoDriver.
1348
+ * @hidden
1349
+ */
1350
+ interface MongoDriverOnErrorContext {
1351
+ /**
1352
+ * Lỗi phát sinh.
1353
+ *
1354
+ * Có thể là bất kỳ kiểu nào (`unknown`),
1355
+ * nên cần type guard hoặc cast khi xử lý.
1356
+ */
1357
+ error: unknown;
1358
+ /**
1359
+ * Tên database tại thời điểm xảy ra lỗi.
1360
+ */
1361
+ databaseName: string;
1362
+ /**
1363
+ * Tên collection tại thời điểm xảy ra lỗi.
1364
+ */
1365
+ collectionName: string;
1366
+ }
1313
1367
  /**
1314
1368
  * Cấu hình cho MongoDriver.
1315
1369
  */
@@ -1332,6 +1386,21 @@ interface MongoDriverOptions {
1332
1386
  * @default "json_store"
1333
1387
  */
1334
1388
  collectionName?: string;
1389
+ /**
1390
+ * Callback khi kết nối thành công.
1391
+ */
1392
+ onLoad?: (ctx: MongoDriverOnLoadContext) => any;
1393
+ /**
1394
+ * Callback khi xảy ra lỗi.
1395
+ */
1396
+ onError?: (ctx: MongoDriverOnErrorContext) => any;
1397
+ }
1398
+ /**
1399
+ * Schema document dùng để lưu trữ database trong MongoDB.
1400
+ */
1401
+ interface DatabaseDocument<V = any> {
1402
+ _id: string;
1403
+ data: V;
1335
1404
  }
1336
1405
  /**
1337
1406
  * Driver lưu trữ dữ liệu bằng MongoDB.
@@ -1354,11 +1423,21 @@ interface MongoDriverOptions {
1354
1423
  *
1355
1424
  * @example
1356
1425
  * ```ts
1426
+ * import { Database, MongoDriver } from "blackcat.js-database";
1427
+ *
1357
1428
  * const database = new Database({
1358
1429
  * driver: new MongoDriver({
1359
1430
  * mongourl: "mongodb://localhost:27017",
1360
1431
  * databaseName: "mydb",
1361
- * collectionName: "store"
1432
+ * collectionName: "store",
1433
+ * onLoad: ({ db, collection, databaseName }) => {
1434
+ * console.log(`✅ Đã kết nối với cơ sở dữ liệu: ${databaseName}`);
1435
+ * console.log(`📦 Bộ sưu tập: ${collection.collectionName}`);
1436
+ * },
1437
+ * onError: ({ error, databaseName }) => {
1438
+ * console.error(`❌ Không thể kết nối với cơ sở dữ liệu: ${databaseName}`);
1439
+ * console.error(error);
1440
+ * }
1362
1441
  * })
1363
1442
  * });
1364
1443
  * ```
@@ -1384,6 +1463,18 @@ declare class MongoDriver implements DatabaseDriver {
1384
1463
  * Tên collection MongoDB.
1385
1464
  */
1386
1465
  private collectionName;
1466
+ /**
1467
+ * Callback khi kết nối thành công.
1468
+ */
1469
+ onLoad?: (ctx: MongoDriverOnLoadContext) => any;
1470
+ /**
1471
+ * Callback khi xảy ra lỗi.
1472
+ */
1473
+ onError?: (ctx: MongoDriverOnErrorContext) => any;
1474
+ /**
1475
+ * Trạng thái đã gọi onLoad chưa (tránh spam)
1476
+ */
1477
+ private isLoaded;
1387
1478
  /**
1388
1479
  * Khởi tạo MongoDriver.
1389
1480
  *
@@ -1391,11 +1482,21 @@ declare class MongoDriver implements DatabaseDriver {
1391
1482
  *
1392
1483
  * @example
1393
1484
  * ```ts
1485
+ * import { Database, MongoDriver } from "blackcat.js-database";
1486
+ *
1394
1487
  * const database = new Database({
1395
1488
  * driver: new MongoDriver({
1396
1489
  * mongourl: "mongodb://localhost:27017",
1397
1490
  * databaseName: "mydb",
1398
- * collectionName: "store"
1491
+ * collectionName: "store",
1492
+ * onLoad: ({ db, collection, databaseName }) => {
1493
+ * console.log(`✅ Đã kết nối với cơ sở dữ liệu: ${databaseName}`);
1494
+ * console.log(`📦 Bộ sưu tập: ${collection.collectionName}`);
1495
+ * },
1496
+ * onError: ({ error, databaseName }) => {
1497
+ * console.error(`❌ Không thể kết nối với cơ sở dữ liệu: ${databaseName}`);
1498
+ * console.error(error);
1499
+ * }
1399
1500
  * })
1400
1501
  * });
1401
1502
  */
@@ -1423,4 +1524,4 @@ declare class MongoDriver implements DatabaseDriver {
1423
1524
  delete(): Promise<boolean>;
1424
1525
  }
1425
1526
 
1426
- export { Database, JSONDriver, MemoryDriver, MongoDriver, SQLiteDriver };
1527
+ export { Database, type DatabaseDriver, JSONDriver, MemoryDriver, MongoDriver, SQLiteDriver };