Press n or j to go to the next uncovered block, b, p or k for the previous block.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 | 1x 1x 1x 1x 1x 1x 1x 430x 430x 430x 430x 430x 430x 430x 430x 430x 430x 430x 430x 430x 780x 780x 430x 425x 425x 425x 425x 425x 430x 445x 445x 430x 175x 15x 15x 160x 160x 175x 175x 175x 175x 175x 430x 180x 15x 15x 165x 165x 180x 180x 180x 180x 180x 430x 145x 10x 10x 135x 135x 145x 130x 130x 130x 130x 5x 5x 5x 125x 125x 125x 125x 125x 125x 5x 145x 430x 105x 10x 10x 95x 95x 105x 90x 90x 90x 90x 5x 5x 5x 85x 85x 85x 85x 85x 85x 5x 105x 430x 80x 80x 30x 30x 50x 80x 70x 70x 70x 25x 25x 25x 45x 45x 45x 45x 45x 45x 80x 80x 430x 85x 85x 35x 35x 50x 85x 70x 70x 70x 25x 25x 25x 45x 45x 45x 45x 45x 45x 85x 85x 430x 35x 35x 35x 10x 10x 35x 35x 35x 35x 35x 25x 35x 430x 40x 40x 40x 15x 15x 40x 35x 35x 35x 35x 25x 40x 430x 30x 10x 10x 20x 30x 10x 10x 10x 10x 30x 430x 30x 10x 10x 20x 30x 10x 10x 10x 10x 30x 430x 380x 380x 40x 40x 40x 35x 35x 5x 5x 5x 35x 30x 30x 5x 5x 72x 380x 430x 90x 90x 45x 45x 45x 40x 40x 5x 5x 5x 40x 35x 35x 5x 5x 15x 90x 430x 40x 40x 50x 50x 50x 50x 40x 40x 40x 430x 40x 40x 50x 50x 50x 50x 40x 40x 430x 15x 15x 430x 15x 15x 430x 21x 21x 21x 21x 21x 21x 21x 21x 21x 21x 430x 5x 5x 430x | import { get as _get, set as _set, unset as _unset } from "lodash"; import { StorageFactory } from "./StorageFactory"; import type { DataGetModel, DataModel, KeyPath, Options, RecordType, StorageBase, TTL, ValueType } from "./types"; import { StorageEngine } from "./types"; import { Utils } from "./utils"; /** * @internal */ const defaultOptions: Options = { ttl: { seconds: 0, minutes: 0, hours: 1, days: 0 }, removeExpired: true, storage: StorageEngine.Auto, }; /** * Represents a hybrid web cache that supports both asynchronous and synchronous * operations for storing, retrieving, and managing key-value pairs with optional * time-to-live (TTL) settings. * * The cache can automatically remove expired entries * and supports various storage engines. * * Provides methods for setting, getting, * checking existence, and unsetting values, as well as resetting the cache with * new data. Includes utility functions for converting TTL and calculating storage * size. * @author Heliomar Marques * @example * * Basic Usage with Default Options (storage: Auto, ttl: 1 hour) * ```ts * import { HybridWebCache, StorageEngine } from 'hybrid-webcache'; * * const cache = new HybridWebCache(); * * await cache.set('sessionToken', 'abc123'); * const tokenData = await cache.get<string>('sessionToken'); * console.log(`Token: ${tokenData?.value}`); // Output: Token: abc123 * console.log(`Is Expired: ${tokenData?.isExpired}`); // Output: Is Expired: false * ``` * @example * Creating an instance with custom options (e.g., IndexedDB, 10-minute TTL) * ```ts * import { HybridWebCache, StorageEngine } from 'hybrid-webcache'; * * // Note: For IndexedDB, remember to call .init() if you plan to use synchronous methods * const indexedDBCache = new HybridWebCache('myAppCache', { * storage: StorageEngine.IndexedDB, * ttl: { minutes: 10 }, * removeExpired: true, * }); * * await indexedDBCache.init(); // Initialize IndexedDB to load memory cache for sync operations * //Setting and Getting Nested Data * await indexedDBCache.set('user.profile.firstName', 'John', { hours: 1 }); * indexedDBCache.setSync('user.profile.lastName', 'Doe'); // Uses instance's default TTL (10 minutes) * indexedDBCache.setSync(['user', 'profile', 'age'], 30); // Array KeyPath * * const userData = await indexedDBCache.get('user.profile'); * console.log(userData?.value); // Output: { firstName: 'John', lastName: 'Doe', age: 30 } * const firstNameData = indexedDBCache.getSync('user.profile.firstName'); * console.log(firstNameData?.value); // Output: John * * // Checking for Key Existence * const hasUser = await indexedDBCache.has('user.profile.firstName'); * console.log(`Has user first name: ${hasUser}`); // Output: Has user first name: true * * const hasNonExistentKey = indexedDBCache.hasSync('non.existent.key'); * console.log(`Has non-existent key: ${hasNonExistentKey}`); // Output: Has non-existent key: false * * // Unsetting Data (Partial and Full) * const complexObject = { * theme: 'dark', * settings: { * language: 'en-US', * notifications: { email: true, sms: false } * } * }; * await indexedDBCache.set('appConfig', complexObject); * * // Unset a nested property * await indexedDBCache.unset('appConfig.settings.notifications.sms'); * const updatedAppConfig = await indexedDBCache.get('appConfig'); * console.log(updatedAppConfig?.value); * // Output: { theme: 'dark', settings: { language: 'en-US', notifications: { email: true } } } * * // Unset an array element (sets to null) * indexedDBCache.unsetSync('appConfig.items[1]'); * const updatedItems = indexedDBCache.getSync('appConfig.items'); * console.log(updatedItems?.value); // Output: ['apple', null, 'orange'] * * // Unset the entire 'appConfig' key * await indexedDBCache.unset('appConfig'); * const appConfigAfterUnset = await indexedDBCache.get('appConfig'); * console.log(appConfigAfterUnset); // Output: undefined * * // Retrieving All Data * await indexedDBCache.set('product1', { id: 1, name: 'Laptop' }); * await indexedDBCache.set('product2', { id: 2, name: 'Mouse' }); * * const allItemsMap = await indexedDBCache.getAll(); * console.log(allItemsMap); * /* Output: * Map(2) { * 'product1' => { value: { id: 1, name: 'Laptop' }, expiresAt: ..., isExpired: false }, * 'product2' => { value: { id: 2, name: 'Mouse' }, expiresAt: ..., isExpired: false } * } * *\/ * * const allItemsJson = indexedDBCache.getJsonSync(); * console.log(allItemsJson); * /* Output: * { product1: { id: 1, name: 'Laptop' }, * product2: { id: 2, name: 'Mouse' } * } *\/ * * // Resetting the Cache * await indexedDBCache.resetWith({ * user: { id: 'user123', status: 'active' }, * app: { version: '1.0.0' } * }, { minutes: 5 }); // New TTL for reset * * const resetData = await indexedDBCache.getJson(); * console.log(resetData); * /* Output: * { * user: { id: 'user123', status: 'active' }, * app: { version: '1.0.0' } * } *\/ * * // Getting Cache Info * const cacheInfo = indexedDBCache.info; * console.log(cacheInfo); * /* Output: * { * dataBase: 'myAppCache', * size: 'XXb', // e.g., '120b' * options: { * ttl: 300000, // 5 minutes in ms * removeExpired: true, * storage: 2 // StorageEngine.IndexedDB * } * } *\/ * ``` * * @category Core */ export class HybridWebCache { /** * Basename * @private */ private baseName: string; /** * The options for the Cache. * @type {@link Options} * @private */ private options: Options; /** @ignore */ private storageBase: StorageBase; /** * Constructor for Hybrid WebCache. * * To reset the cache, use [`resetWith()`|`resetWithSync()`]. * * _**Note:**_ For `StorageType.IndexedDB`, remember to call .init() if you plan to use synchronous methods * * @param {string} [baseName='HybridWebCache'] - The base name of the cache. * @param {Partial<Options>} options * @default * ```ts * //options * { * ttl: { seconds: 0, minutes: 0, hours: 1, days: 0 }, * removeExpired: true, * storage: StorageType.Auto * } * ``` */ constructor(baseName = "HybridWebCache", options?: Partial<Options>) { this.baseName = baseName; this.options = { ...defaultOptions, ...options }; this.storageBase = this.determineStorageEngine(this.options.storage); this.options.storage = this.storageBase.type; } private determineStorageEngine(storage: StorageEngine): StorageBase { return StorageFactory.createStorage(storage, this.baseName); } private createKey(keyPath: KeyPath): string { return Utils.getKey(keyPath); } private prepareDataSet<T extends ValueType>(value: T, ttl: Partial<TTL> = this.options.ttl) { const ttlMs = Utils.convertTTLToMilliseconds(ttl); const expiresAt = ttlMs > 0 ? Date.now() + ttlMs : 0; const data: DataModel<T> = { value, expiresAt }; return { data }; } /** * Initializes the memory cache * * This method is only necessary to use the synchronous functions of the IndexedDB strategy. * * @return A promise that resolves when the local storage is initialized. * * @example * * ```ts * const cache = new HybridWebCache("CacheDB", {storage: StorageEngine.IndexedDB}); * await cache.init(); * ``` * * @category Init Method */ public async init(): Promise<void> { await this.storageBase.init(); } /** * Sets the value for a given keyPath in the storage engine. * * If the keyPath already exists, its value is updated with the provided * value. If the keyPath does not exist, a new entry is created with the * provided TTL. * * @template {@link ValueType} T - The type of the value being stored. * @param {@link KeyPath} keyPath - The keyPath to be stored. * @param {@link ValueType} value - The value to be stored. * @param {@link TTL} ttl - Optional TTL settings for the stored value. Defaults to * the instance's configured TTL. * * @example * * Change the value at `color.name` to `sapphire`. * ```ts * // Given: * { * "color": { * "name": "cerulean", * "code": { * "rgb": [0, 179, 230], * "hex": "#003BE6" * } * } * } * * const cache = new HybridWebCache(); * await cache.set('color.name', 'sapphire'); * ``` * @example * * Set the value of `color.hue` to `bluish`. * ```ts * const cache = new HybridWebCache(); * await cache.set(['color', 'hue'], 'bluish); * ``` * @example * * Change the value of `color.code`. * ```ts * const cache = new HybridWebCache(); * await cache.set('color.code', { rgb: [16, 31, 134], hex: '#101F86' }); * ``` * * @category Set Methods */ async set<T extends ValueType>(keyPath: KeyPath, value: T, ttl: Partial<TTL> = this.options.ttl): Promise<void> { if (keyPath === undefined || keyPath === null) { throw new Error("KeyPath cannot be undefined or null."); } const key = this.createKey(keyPath); const data = await this.storageBase.get(key); const obj = data?.value || {}; _set(obj as object, keyPath, value); const dataSet = this.prepareDataSet(obj, ttl); return this.storageBase.set(key, dataSet.data); } /** * Synchronous version of set. * * @template {@link ValueType} T - The type of the value being stored. * @param {@link KeyPath} keyPath - The keyPath to be stored. * @param {@link ValueType} value - The value to be stored. * @param {@link TTL} ttl - Optional TTL settings for the stored value. Defaults to * the instance's configured TTL. * * @example * * Change the value at `color.name` to `sapphire`. * ```ts * // Given: * { * "color": { * "name": "cerulean", * "code": { * "rgb": [0, 179, 230], * "hex": "#003BE6" * } * } * } * cache.setSync('color.name', 'sapphire'); * ``` * @example * * Set the value of `color.hue` to `bluish`. * ```ts * cache.setSync(['color', 'hue'], 'bluish); * ``` * @example * * Change the value of `color.code`. * ```ts * cache.setSync('color.code', { rgb: [16, 31, 134], hex: '#101F86' }); * ``` * * @category Set Methods */ setSync<T extends ValueType>(keyPath: KeyPath, value: T, ttl: Partial<TTL> = this.options.ttl): void { if (keyPath === undefined || keyPath === null) { throw new Error("KeyPath cannot be undefined or null."); } const key = this.createKey(keyPath); const data = this.storageBase.getSync(key); const obj = data?.value || {}; _set(obj as object, keyPath, value); const dataSet = this.prepareDataSet(obj, ttl); this.storageBase.setSync(key, dataSet.data); } /** * Retrieves the value associated with the specified keyPath from the storage engine. * * If the value is found, it returns an object containing the value, expiration time, * and expiration status. If the value is expired and the `removeExpired` flag is set * to true, the expired value is removed from storage and `undefined` is returned. * * @template T - The type of the value being retrieved. * @param {@link KeyPath} keyPath - The path to the key whose value should be retrieved. * @param {boolean} removeExpired - A flag indicating whether to remove the key if its value * is expired. Defaults to the instance's configured setting. * @returns A promise that resolves to an object containing the value and its metadata, * or `undefined` if the value does not exist or is expired and removed. * * @example * * Get the value at `color.name`. * ```ts * // Given: * { * "color": { * "name": "cerulean", * "code": { * "rgb": [0, 179, 230], * "hex": "#003BE6" * } * } * } * const cache = new HybridWebCache(); * const value = await cache.get('color.name'); * // => "cerulean" * ``` * @example * * Get the value at `color.code.hex`. * ```ts * const hex = await cache.get('color.color.hex'); * // => "#003BE6" * ``` * @example * * Get the value at `color.hue`. * ```ts * const value = await cache.get(['color', 'hue']); * // => undefined * ``` * @example * * Get the value at `color.code.rgb[1]`. * ```ts * const value = await cache.get('color.code.rgb[1]'); * // => 179 * ``` * * @category Get Methods */ async get<T extends ValueType>(keyPath: KeyPath, removeExpired: boolean = this.options.removeExpired): Promise<DataGetModel<T> | undefined> { if (keyPath === undefined || keyPath === null) { throw new Error("KeyPath cannot be undefined or null."); } const key = this.createKey(keyPath); const data = await this.storageBase.get(key); if (data) { const value = _get(data.value, keyPath); if (value === undefined) { return; } const isExpired = Utils.isExpired(data.expiresAt); if (removeExpired && isExpired) { await this.unset(keyPath); return; } return { value, expiresAt: data.expiresAt, isExpired, } as DataGetModel<T>; } return; } /** * Synchronous version of get. * * Retrieves the value associated with the specified keyPath from the storage engine. * * If the value is found, it returns an object containing the value, expiration time, * and expiration status. If the value is expired and the `removeExpired` flag is set * to true, the expired value is removed from storage and `undefined` is returned. * * @template T - The type of the value being retrieved. * @param {@link KeyPath} keyPath - The path to the key whose value should be retrieved. * @param {boolean} removeExpired - A flag indicating whether to remove the key if its value * is expired. Defaults to the instance's configured setting. * @returns An object containing the value and its metadata, or `undefined` if the * value does not exist or is expired and removed. * @example * * Get the value at `color.name`. * ```ts * // Given: * { * "color": { * "name": "cerulean", * "code": { * "rgb": [0, 179, 230], * "hex": "#003BE6" * } * } * } * * const value = cache.getSync('color.name'); * // => "cerulean" * ``` * @example * * Get the value at `color.code.hex`. * ```ts * const hex = cache.getSync('color.color.hex'); * // => "#003BE6" * ``` * @example * * Get the value at `color.hue`. * ```ts * const value = cache.getSync(['color', 'hue']); * // => undefined * ``` * @example * * Get the value at `color.code.rgb[1]`. * ```ts * const value = cache.getSync('color.code.rgb[1]'); * // => 179 * ``` * * @category Get Methods */ getSync<T extends ValueType>(keyPath: KeyPath, removeExpired: boolean = this.options.removeExpired): DataGetModel<T> | undefined { if (keyPath === undefined || keyPath === null) { throw new Error("KeyPath cannot be undefined or null."); } const key = this.createKey(keyPath); const data = this.storageBase.getSync(key); if (data) { const value = _get(data.value, keyPath); if (value === undefined) { return; } const isExpired = Utils.isExpired(data.expiresAt); if (removeExpired && isExpired) { this.unsetSync(keyPath); return; } return { value, expiresAt: data.expiresAt, isExpired, } as DataGetModel<T>; } return; } /** * Retrieves all key-value pairs from the storage engine. * * If the `removeExpired` flag is set to true, expired values are removed from storage * before being returned. * * @param {boolean} removeExpired - A flag indicating whether to remove expired values from storage. * Defaults to the instance's configured setting. * @returns A map of key-value pairs, where each value is an object containing the value, * expiration time, and expiration status. If no values are found or if all values * are expired and removed, `null` is returned. * * @category Get Methods */ async getAll<T extends ValueType>(removeExpired: boolean = this.options.removeExpired): Promise<Map<string, DataGetModel<T>> | null> { const allItems = await this.storageBase.getAll(); if (!allItems) { return null; } const result: Map<string, DataGetModel<T>> = new Map(); for (const [key, data] of allItems) { const [iKey, iValue] = Object.entries(data.value ?? { key, value: null })[0]; // Check if the item is expired const isExpired = Utils.isExpired(data.expiresAt); // If `removeExpired` is true and the item is expired, remove it and skip adding to result if (removeExpired && isExpired) { await this.unset(iKey); continue; } result.set(iKey, { value: iValue as T, expiresAt: data.expiresAt, isExpired, }); } return Promise.resolve(result.size > 0 ? result : null); } /** * Synchronously retrieves all items from storage as a map of key-value pairs, * where each value is an object containing the value, expiration time, and expiration status. * * If the `removeExpired` flag is set to true, expired values are removed from storage * before being returned. * * @param {boolean} removeExpired - A flag indicating whether to remove expired values from storage. * Defaults to the instance's configured setting. * @returns A map of key-value pairs, where each value is an object containing the value, * expiration time, and expiration status. If no values are found or if all values * are expired and removed, `null` is returned. * * @category Get Methods */ getAllSync<T extends ValueType>(removeExpired: boolean = this.options.removeExpired): Map<string, DataGetModel<T>> | null { const allItems = this.storageBase.getAllSync(); if (!allItems) { return null; } const result: Map<string, DataGetModel<T>> = new Map(); for (const [key, data] of allItems) { const [iKey, iValue] = data.value ? Object.entries(data.value)[0] : [key, null]; // Check if the item is expired const isExpired = Utils.isExpired(data.expiresAt); // If `removeExpired` is true and the item is expired, remove it and skip adding to result if (removeExpired && isExpired) { this.unsetSync(iKey); continue; } result.set(iKey, { value: iValue as T, expiresAt: data.expiresAt, isExpired, }); } return result.size > 0 ? result : null; } /** * Asynchronously retrieves all key-value pairs from the storage as a JSON object. * * If the `removeExpired` flag is set to true, expired values are removed from storage * before being included in the result. * * @param {boolean} removeExpired - A flag indicating whether to remove expired values from storage. * Defaults to the instance's configured setting. * @returns A promise that resolves to a JSON object containing all key-value pairs. * If no items are found or all items are expired and removed, `null` is returned. * * @category Get Methods */ async getJson(removeExpired: boolean = this.options.removeExpired): Promise<Record<string, ValueType> | null> { const allValues: Record<string, ValueType> = {}; const allItems = await this.getAll(removeExpired); if (!allItems) { return null; } for (const [key, data] of allItems) { if (data && data.value !== undefined) { allValues[key] = data.value; } } return allValues; } /** * Synchronously retrieves all key-value pairs from the storage as a JSON object. * * If the `removeExpired` flag is set to true, expired values are removed from storage * before being included in the result. * * @param {boolean} removeExpired - A flag indicating whether to remove expired values from storage. * Defaults to the instance's configured setting. * @returns A JSON object containing all key-value pairs. If no items are found or all * items are expired and removed, `null` is returned. * * @category Get Methods */ getJsonSync(removeExpired: boolean = this.options.removeExpired): Record<string, ValueType> | null { const allValues: Record<string, ValueType> = {}; const allItems = this.getAllSync(removeExpired); if (!allItems) { return null; } for (const [key, data] of allItems) { if (data && data.value !== undefined) { allValues[key] = data.value; } } return allValues; } /** * Checks if the given key path exists. * * _For sync method, use_ [`hasSync()`]. * * @param {@link KeyPath} keyPath The key path to check. * @returns A promise which resolves to `true` if the `keyPath` exists, else `false`. * @example * * Check if the value at `color.name` exists. * ```ts * // Given: * { * "color": { * "name": "cerulean", * "code": { * "rgb": [0, 179, 230], * "hex": "#003BE6" * } * } * } * * const exists = await cache.has('color.name'); * // => true * ``` * @example * * Check if the value at `color.hue` exists. * ```ts * const exists = await cache.has(['color', 'hue']); * // => false * ``` * @example * * Check if the value at `color.code.rgb[1]` exists. * ```ts * const exists = await cache.has(color.code.rgb[1]); * // => true * ``` * * @category Has Methods */ async has(keyPath: KeyPath): Promise<boolean> { if (keyPath === undefined || keyPath === null) { throw new Error("KeyPath cannot be undefined or null."); } const key = this.createKey(keyPath); if (key === keyPath.toString()) { return this.storageBase.has(key); } const data = await this.get(keyPath); return data !== undefined && data?.value !== null; } /** * Checks if the given key path exists. * * _For async method, use_ [`has()`]. * * @param {@link KeyPath} keyPath The key path to check. * @returns `true` if the `keyPath` exists, else `false`. * @example * * Check if the value at `color.name` exists. * ```ts * // Given: * { * "color": { * "name": "cerulean", * "code": { * "rgb": [0, 179, 230], * "hex": "#003BE6" * } * } * } * * const exists = cache.hasSync('color.name'); * // => true * ``` * @example * * Check if the value at `color.hue` exists. * ```ts * const exists = cache.hasSync(['color', 'hue']); * // => false * ``` * @example * * Check if the value at `color.code.rgb[1]` exists. * ```ts * const exists = cache.hasSync(color.code.rgb[1]); * // => true * ``` * * @category Has Methods */ hasSync(keyPath: KeyPath): boolean { if (keyPath === undefined || keyPath === null) { throw new Error("KeyPath cannot be undefined or null."); } const key = this.createKey(keyPath); if (key === keyPath.toString()) { return this.storageBase.hasSync(key); } const data = this.getSync(keyPath); return data !== undefined && data?.value !== null; // return data !== undefined && data?.value !== null; // return _has(data?.value, keyPath); } /** * Unsets all key values. * * _For sync method, use_ [`unsetSync()`]. * * @returns A promise which resolves when the key values have been unset. * @example * * Unsets all key values. * ```ts * await cache.unset(); * await cache.getAll(); * // => undefined * ``` * * @category Unset Methods */ unset(): Promise<boolean>; /** * Unsets the property at the given key path. * * _For sync method, use_ [`unsetSync()`]. * * @param {@link KeyPath} keyPath The key path of the property. * @returns A promise which resolves when the setting has been unset. * @example * * Unset the property `color.name`. * ```ts * // Given: * { * "color": { * "name": "cerulean", * "code": { * "rgb": [0, 179, 230], * "hex": "#003BE6" * } * } * } * * await cache.unset('color.name'); * await cache.get('color.name'); * // => undefined * ``` * @example * * Unset the property `color.code.rgba[1]`. * ```ts * await cache.unset('color.code.rgba[1]'); * await cache.get('color.code.rgb'); * // => [0, null, 230] * ``` * * @category Unset Methods */ async unset(keyPath: KeyPath): Promise<boolean>; async unset(keyPath?: KeyPath): Promise<boolean> { if (this.storageBase.length === 0) return false; if (keyPath) { const key = this.createKey(keyPath); const data = await this.storageBase.get(key); if (data) { if (_unset(data.value, keyPath)) { if (Object.keys(data.value || {}).length > 0) { //update await this.storageBase.set(key, data); return true; } } return this.storageBase.unset(key); } return false; } return this.storageBase.unset(); } /** * Unsets all key values. * * _For async method, use_ [`unset()`]. * * @example * * Unsets all key values. * ```ts * cache.unsetSync(); * ``` * * @category Unset Methods */ unsetSync(): boolean; /** * Unsets the property at the given key path. * * _For async method, use_ [`unset()`]. * * @param {@link KeyPath} keyPath The key path of the property. * @example * * Unset the property `color.name`. * ```ts * // Given: * { * "color": { * "name": "cerulean", * "code": { * "rgb": [0, 179, 230], * "hex": "#003BE6" * } * } * } * * cache.unsetSync('color.name'); * cache.getSync('color.name'); * // => undefined * ``` * @example * * Unset the property `color.code.rgba[1]`. * ```ts * cache.unsetSync('color.code.rgba[1]'); * cache.getSync('color.code.rgb'); * // => [0, null, 230] * ``` * * @category Unset Methods */ unsetSync(keyPath: KeyPath): boolean; unsetSync(keyPath?: KeyPath): boolean { if (this.storageBase.length === 0) return false; if (keyPath) { const key = this.createKey(keyPath); const data = this.storageBase.getSync(key); if (data) { if (_unset(data.value, keyPath)) { if (Object.keys(data.value || {}).length > 0) { //update this.storageBase.setSync(key, data); return true; } } return this.storageBase.unsetSync(key); } return false; } return this.storageBase.unsetSync(); } /** * Resets the storage with the provided key-value pairs and optional TTL. * * This method first clears all existing entries in the storage engine. * It then iterates over the provided key-value pairs, setting each one * in the storage with the specified TTL. If no TTL is provided, the * default TTL from the options is used. * * @template T - The type of values being stored. * @param {@link KeyPath} keyValues - An object containing key-value pairs to be stored. * @param {@link TTL} ttl - Optional TTL settings for the stored values. Defaults to * the instance's configured TTL. * @returns A promise that resolves when all key-value pairs have been * set in the storage. * * @category Reset Data Methods */ async resetWith<T extends ValueType>(keyValues: RecordType<T>, ttl: Partial<TTL> = this.options.ttl): Promise<void> { await this.storageBase.unset(); const promises = Object.entries(keyValues).map(([key, value]) => { const obj: object = {}; _set(obj, key, value); const dataSet = this.prepareDataSet<T>(obj as T, ttl); return this.storageBase.set(this.createKey(key), dataSet.data); }); await Promise.all(promises); } /** * Resets the storage with the provided key-value pairs and optional TTL. * * This method first clears all existing entries in the storage engine. * It then iterates over the provided key-value pairs, setting each one * in the storage with the specified TTL. If no TTL is provided, the * default TTL from the options is used. * * @template T - The type of values being stored. * @param {@link KeyPath} keyValues - An object containing key-value pairs to be stored. * @param {@link TTL} ttl - Optional TTL settings for the stored values. Defaults to * the instance's configured TTL. * * @category Reset Data Methods */ resetWithSync<T extends ValueType>(keyValues: RecordType<T>, ttl: Partial<TTL> = this.options.ttl): void { this.storageBase.unsetSync(); Object.entries(keyValues).forEach(([key, value]) => { const obj: object = {}; _set(obj, key, value); const dataSet = this.prepareDataSet<T>(obj as T, ttl); this.storageBase.setSync(this.createKey(key), dataSet.data); }); } /** * Retrieves the number of items currently stored in the cache. * * @returns The count of items in the storage. * * @category Auxiliary Methods */ get length(): number { return this.storageBase.length; } /** * Retrieves the total number of bytes used by the cache in the storage. * * @returns The total bytes used by the cache. * @category Auxiliary Methods */ get bytes(): number { return this.storageBase.bytes; } /** * Provides information about the current cache. * * @returns An object containing: * - `dataBase`: The name of the database used by the cache. * - `size`: The calculated storage size in bytes represented as a string. * - `options`: The current cache options including TTL converted to milliseconds. * * ```ts * { * dataBase: 'myAppCache', * size: 'XXb', // e.g., '120b' * options: { * ttl: 300000, // 5 minutes in ms * removeExpired: true, * storage: 2 // StorageEngine.IndexedDB * } * } * ``` * * @category Auxiliary Methods */ get info(): { dataBase: string; size: string; options: Options } { const size = Utils.calculateStorageSize(this.storageBase.bytes); return { dataBase: this.baseName, size, options: { ...this.options, ttl: Utils.convertTTLToMilliseconds(this.options.ttl), }, }; } /** * Returns the type of storage engine used by the cache. * * @returns The type of storage engine used by the cache. * @category Auxiliary Methods */ get storageType(): StorageEngine { return this.storageBase.type; } } |