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 | 9x 9x 9x 9x 37x 6x 9x 21x 21x 21x 21x 21x 21x 21x 21x 21x 1x 10x 10x 10x 2x 10x 2x 10x 10x 19x 19x 19x 9x 9x 18x 9x 9x 9x 36x 36x 36x 15x 15x 15x 21x 17x 17x 17x 17x 17x 17x 17x 17x 7x 10x 10x 10x 1x 1x 16x 2x 2x 2x 2x 2x 2x 1x 1x 1x 2x 2x 4x 4x 4x 9x 9x 1x 8x 3x 5x 8x 3x 5x 7x 7x 7x 7x 1x 6x 7x 6x 6x 6x 1x 5x 6x 9x 16x 16x 16x 16x 16x 16x 16x 25x 2x 16x 58x 10x 10x 10x 10x 13x 13x 10x 13x 1x 1x 3x 1x 2x 2x 2x 2x 2x 8x 1x 7x 7x 2x 5x 5x 5x 1x 1x 2x 2x 2x 2x 2x 1x 1x 2x 2x 2x 2x 2x 2x 4x 4x 4x 1x 3x 3x 2x 2x 2x 1x 1x 1x 1x 1x 2x 2x 1x 1x 1x 1x 10x 10x 1x 1x 2x 2x 10x 10x 10x 10x 10x 10x 10x 10x 10x 1x 1x 1x 1x 1x 1x 2x 1x 1x 1x 1x 1x 1x 1x 1x 2x 1x 11x 11x 11x 11x 11x 11x 11x 9x 97x 97x 14x 14x 4x 10x 10x 19x 19x 4x 15x 15x 1x 14x 13x 13x 1x 60x 9x 34x 10x 10x 7x 7x 2x 2x 9x 26x 3x 2x 1x 8x 8x 8x 8x 8x 8x 5x 5x 5x 5x 5x 5x 5x 1x 8x 8x 2x 1x 1x 1x 4x 1x 1x 3x 2x 1x 1x 1x 6x 6x 6x 6x 6x 18x 18x 1x 18x 6x 15x 6x 18x 6x 6x 18x 18x 6x 6x | import { Injectable } from '@angular/core';
import { storeService } from "@unpispas/upp-base";
import { GenericUtils } from "@unpispas/upp-defs";
/**
* Represents the type of storage, either for metadata or data.
*/
type StorageType = 'META' | 'DATA';
/**
* Abstract base class for a storage system.
* Defines the common interface for various storage implementations.
*/
export abstract class StorageDDBB {
protected _isopen = false;
/**
* Returns true if the database is open
*/
get IsOpen(): boolean{
return this._isopen;
}
/**
* Retrieves the name of the database.
*/
abstract get ddbbname(): string;
/**
* Opens the storage for operations.
* @returns A promise that resolves to `true` if the storage opens successfully.
*/
abstract Open(): Promise <boolean>;
/**
* Closes the storage and clears any in-memory data.
*/
abstract Close(): void;
/**
* Cleans the storage by removing all entries.
* @returns A promise that resolves to `true` if the operation succeeds.
*/
abstract Clean() : Promise <boolean>;
/**
* Retrieves a specific item from the storage.
* @param key - The key of the item to retrieve.
* @param target - The type of storage (`META` or `DATA`).
* @returns A promise that resolves to the retrieved item, or `null` if not found.
*/
abstract Get(key: string, target: StorageType) : Promise <any>;
/**
* Saves or updates an item in the storage.
* @param key - The key of the item to store.
* @param data - The data to store.
* @param target - The type of storage (`META` or `DATA`).
* @returns A promise that resolves to `true` if the operation succeeds.
*/
abstract Set(key: string, data: any, target: StorageType) : Promise <boolean>;
/**
* Deletes an item from the storage.
* @param key - The key of the item to delete.
* @param target - The type of storage (`META` or `DATA`).
* @returns A promise that resolves to `true` if the operation succeeds.
*/
abstract Del(key: string, target: StorageType) : Promise <boolean>;
/**
* Retrieves all items from the specified storage type.
* @param target - The type of storage (`META` or `DATA`).
* @returns A promise that resolves to an array of all items.
*/
abstract GetAll(target: StorageType) : Promise <Array<any>>;
/**
* Starts a transactional operation on the specified storage type.
* @param target - The type of storage (`META` or `DATA`).
* @throws An error if a transaction is already in progress.
*/
abstract Begin(target: StorageType): void;
/**
* Commits all changes made in a transaction to the storage.
* @param target - The type of storage (`META` or `DATA`).
* @returns A promise that resolves to `true` if the operation succeeds.
* @throws An error if no transaction is in progress.
*/
abstract Flush(target: StorageType): Promise <boolean>
}
/************************************/
/* LOCAL DATABASE (STORAGE) */
/************************************/
/**
* Represents an in-memory cache-based database.
*/
export class CacheDatabase extends StorageDDBB {
private _itemsmeta = new Map <string, any> ();
private _itemsdata = new Map <string, any> ();
private _stores: string [] = [];
private _transdata: Array <any> | null = null;
private _transmeta: Array <any> | null = null;
/**
* Creates an instance of CacheDatabase.
* @param storagekey - The unique key for the storage instance.
* @param store - The storage service used for persistence.
*/
constructor(private storagekey: string, private store: storeService){
super();
this._stores.push(storagekey + '_meta');
this._stores.push(storagekey + '_data');
}
/**
* Retrieves the name of the database.
*/
get ddbbname(): string {
return this.storagekey;
}
/** @inheritdoc */
async Open(): Promise <boolean> {
const _metaitems = (await this.store.Get(this._stores[0])) || [];
const _dataitems = (await this.store.Get(this._stores[1])) || [];
for(const _item of _metaitems){
this._itemsmeta.set(_item['__ddbb'], _item);
}
for(const _item of _dataitems){
this._itemsdata.set(_item['__ddbb'], _item);
}
this._isopen = true;
return true;
}
/** @inheritdoc */
Close(): void {
this._isopen = false;
this._itemsmeta.clear();
this._itemsdata.clear();
}
/** @inheritdoc */
async Clean() : Promise <boolean> {
const _promises = [];
for (const _store of this._stores){
_promises.push(this.store.Del(_store));
}
await Promise.all(_promises);
this.Close();
return true;
}
/** @inheritdoc */
async Get(key: string, target: StorageType) : Promise <any>{
const _target: Map <string, any> = (target == 'META') ? this._itemsmeta : this._itemsdata;
const _getitem = _target.get(key);
if (_getitem){
const result = Object.assign({}, _getitem);
delete result.__ddbb;
return result;
}
return null;
}
/** @inheritdoc */
async Set(key: string, data: any, target: StorageType) : Promise <boolean> {
const _store = (target == 'META') ? this._stores[0] : this._stores[1];
const _target: Map <string, any> = (target == 'META') ? this._itemsmeta : this._itemsdata;
if (data){
const _oldata = this.Get(key, target);
Iif (JSON.stringify(_oldata) == JSON.stringify(data)){
return true; // no changes;
}
data['__ddbb'] = key;
const _atomic = (target === 'META') ? this._transmeta : this._transdata;
if (_atomic !== null){
_atomic.push(data);
}
else {
_target.set(key, data);
try {
await this.store.Set(_store, Array.from(_target.values()));
}
catch(error){
console.error(error);
return false;
}
}
}
else E{
this.Del(key, target);
}
return true;
}
/** @inheritdoc */
async Del(key: string, target: StorageType) : Promise <boolean> {
const _store = (target == 'META') ? this._stores[0] : this._stores[1];
const _target: Map <string, any> = (target == 'META') ? this._itemsmeta : this._itemsdata;
if (_target.has(key)){
_target.delete(key);
try {
await this.store.Set(_store, [ ..._target.values() ]);
}
catch(error){
console.error(error);
return false;
}
}
return true;
}
/** @inheritdoc */
async GetAll(target: StorageType) : Promise <Array<any>> {
const _target = (target === 'META') ? this._itemsmeta : this._itemsdata;
return Array.from(_target.values()).map(item => {
const result = Object.assign({}, item);
delete result.__ddbb;
return result;
});
}
/** @inheritdoc */
Begin(target: StorageType): void {
const _transaction = (target === 'META') ? this._transmeta : this._transdata;
if (_transaction !== null){
throw new Error("[STORAGE] Already in transaction")
}
if (target === 'META') {
this._transmeta = [];
} else {
this._transdata = [];
}
if (target === 'META'){
this._transmeta = [];
}
else {
this._transdata = [];
}
}
/** @inheritdoc */
async Flush(target: StorageType): Promise<boolean> {
const _store = (target == 'META') ? this._stores[0] : this._stores[1];
const _target: Map <string, any> = (target == 'META') ? this._itemsmeta : this._itemsdata;
const _atomic = (target === 'META') ? this._transmeta : this._transdata;
if ((_atomic === null) || (_atomic.length == 0)){
throw new Error("[STORAGE] not in transaction or transaction is empty")
}
for(const _change of _atomic){
_target.set(_change['__ddbb'], _change);
}
try {
await this.store.Set(_store, Array.from(_target.values()));
}
catch(error){
console.error(error);
return false;
}
if (target === 'META'){
this._transmeta = null;
}
else {
this._transdata = null;
}
return true;
}
}
/************************************/
/* LOCAL DATABASE (INDEXEDDB) */
/************************************/
/**
* Represents a database using the IndexedDB API.
* Provides methods for CRUD operations and transaction handling.
*/
export class IndexedDDBB extends StorageDDBB {
private _stores: string [] = [];
private _transdata: Map <string, any> | null = null;
private _transmeta: Map <string, any> | null = null;
/**
* Creates an instance of IndexedDDBB.
* @param storagekey - The unique key for the IndexedDB storage.
*/
constructor(private storagekey: string){
super();
this._stores.push(storagekey + '_meta');
this._stores.push(storagekey + '_data');
}
private _storage(type: StorageType): string {
return this._stores[(type == 'META') ? 0 : 1];
}
/**
* Retrieves the name of the database.
*/
get ddbbname(): string {
return this.storagekey;
}
private _database: IDBDatabase | null = null;
/**
* Retrieves the current IndexedDB instance.
*/
get database(): IDBDatabase | null {
return this._database;
}
/** @inheritdoc */
async Open(): Promise <boolean> {
try {
this._database = await this.OpenDatabase(this.storagekey);
this._isopen = true;
}
catch(error: any){
console.error(error);
this._isopen = false;
}
return this._isopen;
}
/** @inheritdoc */
Close(): void {
this._isopen = false;
if (this.database){
this.CloseDatabase(this.database);
}
this._database = null;
}
/** @inheritdoc */
async Clean() : Promise <boolean> {
try {
return await this.CleanDatabase(this.storagekey);
}
catch(error: any){
console.error(error);
return false;
}
}
/** @inheritdoc */
async Get(key: string, target: StorageType) : Promise <any> {
if (!this.database){
throw new Error("[STORAGE] Database is not ready for operation");
}
const _transaction = this.database.transaction([ this._storage(target) ], 'readonly');
try {
const _request: IDBRequest = await this.RunInStore(_transaction.objectStore(this._storage(target)), 'get', key);
if (_request){
return _request.result || null;
}
}
catch(error){
console.error("[STORAGE] Error on database action: '" + error + "'");
}
return null;
}
/** @inheritdoc */
async Set(key: string, data: any, target: StorageType) : Promise <boolean> {
if (!this.database){
throw new Error("[STORAGE] Database is not ready for operation");
}
const _atomic = (target === 'META') ? this._transmeta : this._transdata;
if (_atomic !== null){
_atomic.set(key, data);
}
else {
const _transaction = this.database.transaction([ this._storage(target) ], 'readwrite');
try {
return !!(await this.RunInStore(_transaction.objectStore(this._storage(target)), 'put', data, key));
}
catch(error: any){
console.error("[STORAGE] Error on database action: '" + error + "'");
}
return false;
}
return true;
}
/** @inheritdoc */
async Del(key: string, target: StorageType) : Promise <boolean> {
Iif (!this.database){
throw new Error("[STORAGE] Database is not ready for operation");
}
const _transaction = this.database.transaction([ this._storage(target) ], 'readwrite');
try {
return !!(await this.RunInStore(_transaction.objectStore(this._storage(target)), 'delete', key));
}
catch(error: any){
console.error("[STORAGE] Error on database action: '" + error + "'");
}
return false;
}
/** @inheritdoc */
async GetAll(target: StorageType) : Promise <Array<any>> {
Iif (!this.database) {
throw new Error("[STORAGE] Database is not ready for operation");
}
const _transaction = this.database.transaction([ this._storage(target) ], 'readonly');
try {
const _request: IDBRequest = await this.RunInStore(_transaction.objectStore(this._storage(target)), 'getAll');
if (_request){
return _request.result;
}
}
catch(error: any){
console.error("[STORAGE] Error on database action: '" + error + "'");
}
return [];
}
/** @inheritdoc */
Begin(target: StorageType): void {
Iif (!this.database){
throw new Error("[STORAGE] Database is not ready for operation");
}
const _atomic = (target === 'META') ? this._transmeta : this._transdata;
if (_atomic !== null){
throw new Error("[STORAGE] Already in transaction")
}
if (target === 'META'){
this._transmeta = new Map <string, any> ();
}
else E{
this._transdata = new Map <string, any> ();
}
}
/** @inheritdoc */
async Flush(target: StorageType): Promise<boolean> {
Iif (!this.database){
throw new Error("[STORAGE] Database is not ready for operation");
}
const _atomic = (target === 'META') ? this._transmeta : this._transdata;
if ((_atomic === null) || (_atomic.size == 0)){
throw new Error("[STORAGE] not in transaction or transaction is empty")
}
const _transaction = this.database.transaction([ this._storage(target) ], 'readwrite');
try {
const _promises = [];
for (const [key, _change] of _atomic.entries()) {
_promises.push(this.RunInStore(_transaction.objectStore(this._storage(target)), 'put', _change, key))
}
const _result = (await Promise.all(_promises)).every((request) => !!request);
if (_result) {
if (target === 'META'){
this._transmeta = null;
}
else E{
this._transdata = null;
}
}
return _result;
}
catch(error: any){
console.error("[STORAGE] Error on database action: '" + error + "'");
}
return false;
}
/**********************************/
/* PRIVATE METHODS */
/**********************************/
private DatabaseRequest(storagekey: string) : IDBOpenDBRequest{
const _request = indexedDB.open(storagekey);
_request.onupgradeneeded = (event) => {
const _db = (event.target as IDBOpenDBRequest).result;
for (const _store of this._stores){
if (!_db.objectStoreNames.contains(_store)) {
_db.createObjectStore(_store);
}
}
};
_request.onblocked = (event) => {
console.error("[STORAGE] The storage '" + storagekey + "' is blocked!!", event)
}
return _request;
}
private OpenDatabase(storagekey: string): Promise<IDBDatabase> {
return new Promise((resolve, reject) => {
const _request: IDBOpenDBRequest = this.DatabaseRequest(storagekey);
if (_request){
_request.onerror = () => {
reject(_request.error || new Error(`Unknown error opening database '${storagekey}'`));
}
_request.onsuccess = (event) => {
resolve((event.target as IDBOpenDBRequest).result);
}
}
else E{
reject("Error requesting for database '" + storagekey + "'");
}
})
}
private CloseDatabase(database: IDBDatabase): void {
database.close();
}
private async CleanDatabase(storagekey: string) : Promise <boolean> {
let database: IDBDatabase | null = null;
try {
database = this._database;
Iif (!database) {
database = await this.OpenDatabase(storagekey);
}
const _stores: string[] = [];
for (let i = 0; i < database.objectStoreNames.length; i++) {
_stores.push(database.objectStoreNames[i]);
}
Iif (_stores.length == 0){
console.warn(`[STORAGE] No object stores to clean in database '${storagekey}'.`);
return true;
}
const transaction = database.transaction(_stores, "readwrite");
return await new Promise<boolean>((resolve, reject) => {
transaction.oncomplete = () => {
console.info(`[STORAGE] Database '${storagekey}' content cleared successfully.`);
resolve(true);
};
transaction.onerror = (event) => {
console.error(
`[STORAGE] Error clearing database '${storagekey}':`,
(event.target as IDBTransaction).error
);
reject((event.target as IDBTransaction).error || new Error("Unknown transaction error."));
};
for (const store of _stores) {
transaction.objectStore(store).clear();
}
});
}
catch (error) {
console.error(`[STORAGE] Failed to clean database '${storagekey}':`, error);
return false;
}
finally {
Iif (!this._database && database) {
this.CloseDatabase(database);
}
}
}
private RunInStore(store: IDBObjectStore, action: string, ...args: any[]): Promise<IDBRequest> {
return new Promise((resolve, reject) => {
let _action: IDBRequest;
try {
Iif (typeof (store as any)[action] !== "function") {
return reject(new Error(`Invalid action '${action}' for IDBObjectStore`));
}
_action = (store as any)[action](...args);
}
catch (error: any) {
return reject(new Error(`Failed to execute action '${action}' on IDBObjectStore. Error: ${error.message}`));
}
_action.onsuccess = () => {
resolve(_action);
};
_action.onerror = (event: Event) => {
const error = (event.target as IDBRequest).error;
console.error(`[STORAGE]: Error running action '${action}' in IndexedDB. Error:`, error);
reject(error || new Error(`Unknown error running action '${action}'`));
};
});
}
}
/************************************/
/* CACHE SERVICE */
/************************************/
/**
* Provides a service for managing storage in the browser.
* Determines the best storage backend (IndexedDB or in-memory storage) and
* provides an API for accessing, modifying, and managing data.
*/
@Injectable({
providedIn: 'root'
})
export class cacheService {
private _storage_databases = new Map <string, StorageDDBB>();
/**
* Creates an instance of cacheService.
* @param store - A service for browser storage operations.
*/
constructor(private store: storeService){
// nothing to do
}
/************************************/
/* Determine impementation */
/************************************/
/**
* Selects the appropriate storage backend (IndexedDB or in-memory storage).
* Creates and caches the database instance for future use.
*
* @param storagekey - A unique key identifying the storage.
* @returns An instance of `StorageDDBB`.
*/
private database(storagekey: string){
const _indexed = (window.indexedDB) && (('databases' in indexedDB));
if (_indexed){
return new IndexedDDBB(storagekey)
}
else {
console.warn("[STORAGE] indexedDB databases API is not supported in this browser.")
return new CacheDatabase(storagekey, this.store);
}
}
/************************************/
/* Storage access */
/************************************/
/**
* Opens a storage backend for the given key.
* If the storage does not exist, it is created and initialized.
*
* @param storagekey - A unique key identifying the storage.
* @returns A promise resolving to the opened `StorageDDBB` instance.
* @throws An error if the storage cannot be opened or initialized.
*/
async Open(storagekey: string): Promise <StorageDDBB> {
let _database: StorageDDBB | undefined = this._storage_databases.get(storagekey);
if (_database && _database.IsOpen){
return _database;
}
_database = this.database(storagekey);
if (!_database){
throw new Error("[STORAGE] Could not create storage '" + storagekey + "'")
}
if (await _database.Open()){
this._storage_databases.set(storagekey, _database);
return _database;
}
else {
throw new Error("[STORAGE] Could not open storage '" + storagekey + "'")
}
}
}
/************************************/
/* ITEM MANAGEMENT */
/************************************/
/**
* Abstract base class for managing storage items.
* Provides a structure for operations such as retrieving, setting, and deleting items.
*/
abstract class StorageItem {
/**
* Creates an instance of `StorageItem`.
* @param storage - The storage backend used for operations.
* @param indexfnc - A function to calculate the unique key for items.
*/
constructor(protected storage: StorageDDBB, protected indexfnc?: (data: any) => string){
// nothing to do
}
/**
* Retrieves an item from the storage by its key.
* @param key - The key of the item to retrieve.
* @returns A promise resolving to the retrieved item, or `null` if not found.
*/
abstract Get(key: string): Promise <any>;
/**
* Stores an item in the storage.
* @param data - The data to store.
* @returns A promise resolving to `true` if the operation was successful.
*/
abstract Set(data: any) : Promise <boolean>;
/**
* Deletes an item from the storage by its key.
* @param key - The key of the item to delete.
* @returns A promise resolving to `true` if the operation was successful.
*/
abstract Del(key: string) : Promise <boolean>;
}
/**
* Handles the management of metadata in the storage.
* Extends `StorageItem` to provide operations specific to metadata.
*/
export class StorageMeta extends StorageItem {
/**
* Creates an instance of `StorageMeta`.
* @param storage - The storage backend used for metadata operations.
*/
constructor(storage: StorageDDBB){
super(storage, () => { return 'metadata'} )
}
/** @inheritdoc */
Get(): Promise <any> {
Iif (!this.indexfnc){
throw new Error("[CACHE] indexer function has not been provided!")
}
return this.storage.Get(this.indexfnc(null), 'META');
}
/** @inheritdoc */
Set(data: any): Promise <boolean> {
Iif (!this.indexfnc){
throw new Error("[CACHE] indexer function has not been provided!")
}
return this.storage.Set(this.indexfnc(null), data, 'META');
}
/** @inheritdoc */
Del(): Promise <boolean> {
Iif (!this.indexfnc){
throw new Error("[CACHE] indexer function has not been provided!")
}
return this.storage.Del(this.indexfnc(null), 'META');
}
}
export class StorageData extends StorageItem {
constructor(storage: StorageDDBB, indexfnc?: (data: any) => string){
super(storage, indexfnc )
}
/** @inheritdoc */
async Get(key: string): Promise <any> {
const _toread: any = await this.storage.Get(key, 'DATA');
if (_toread){
return this._Decrypt(_toread['data'])
}
}
/** @inheritdoc */
async Set(data: any): Promise <boolean> {
Iif (!this.indexfnc){
throw new Error("[CACHE] indexer function has not been provided!")
}
const _itemkey = this.indexfnc(data);
const _olditem = await this.storage.Get(_itemkey, 'DATA');
const _olddata = _olditem && ('data' in _olditem) ? _olditem['data'] : null;
let _newdata = data;
if (_olddata){
const _olddate: number = ('updated' in _olditem) ? _olditem['updated'] : 0;
let _newdate: number = new Date().getTime();
if ('updated' in data){
const _datestr = GenericUtils.mysqlToDateStr(data['updated']);
if (_datestr){
_newdate = new Date(_datestr).getTime();
}
}
if (_newdate > _olddate){
_newdata = this._Merge(this._Decrypt(_olddata), _newdata);
}
}
const _towrite = {
updated: new Date(('updated' in data) ? data['updated'] : null).getTime(),
data: this._Encrypt(_newdata)
}
return this.storage.Set(_itemkey, _towrite, 'DATA');
}
/** @inheritdoc */
Del(key: string): Promise <boolean> {
return this.storage.Del(key, 'DATA');
}
/** @inheritdoc */
async GetAll(): Promise<Array<any>> {
const _encrypted = await this.storage.GetAll('DATA');
const _decrypted = [];
for (const _item of _encrypted){
_decrypted.push(this._Decrypt(_item.data))
}
return _decrypted;
}
/**********************************/
/* PRIVATE METHODS */
/**********************************/
/**
* Merges two data objects, preserving existing fields and concatenating arrays.
* @param olditem - The existing data object.
* @param newitem - The new data object to merge.
* @returns The merged data object.
*/
private _Merge(olditem: any, newitem: any){
Iif (!olditem){
return newitem; // if no previous item, then merge is the new item
}
const _merged = olditem;
for(const _field in newitem){
if (!(_field in olditem)){
_merged[_field] = newitem[_field];
continue; // not in old item (copied from new)
}
// if not an array: replace with new content
if (!(newitem[_field] instanceof Array)){
_merged[_field] = newitem[_field];
}
// concatenate arrays (do not loose old items)
else {
_merged[_field] = _merged[_field].concat(newitem[_field]);
_merged[_field] = [...new Set(_merged[_field])];
}
}
return _merged;
}
/**
* Encrypts a data object into a Base64 string with obfuscation.
* @param data - The data to encrypt.
* @returns The encrypted string.
*/
private _Encrypt(data: any){
let _data = '';
const _b64 = GenericUtils.stringToBase64(JSON.stringify(data));
if (_b64){
const _pos: Array <number> = [ -1, -1, -1 ];
for (let _idx = 0; _idx < _pos.length; _idx++) {
let _candidate = Math.floor(Math.random() * Math.min(_b64.length, 16));
while (_pos.includes(_candidate)) {
_candidate = Math.floor(Math.random() * Math.min(_b64.length, 16));
}
_pos[_idx] = _candidate;
}
_pos.sort((a:number, b:number) => {
return a - b
});
for (let _idx = 0; _idx < _pos.length; _idx++) {
_data += _pos[_idx].toString(16) + _b64[_pos[_idx]];
}
let _offset = 0;
for (let _idx = 0; _idx < _pos.length; _idx++) {
_data += _b64.slice(_offset, _pos[_idx]);
_offset = _pos[_idx] + 1;
}
_data += _b64.slice(_offset);
}
return _data;
}
/**
* Decrypts an obfuscated Base64 string into a data object.
* @param data - The encrypted string to decrypt.
* @returns The decrypted data object.
*/
private _Decrypt(data: string): any{
let _data = '';
const _pos: Array <number> = [
parseInt(data[0], 16),
parseInt(data[2], 16),
parseInt(data[4], 16)
];
const _val: Array <string> = [
data[1],
data[3],
data[5]
]
const _b64 = data.slice(6).split('');
for (let _idx = 0; _idx < _pos.length; _idx++) {
_b64.splice(_pos[_idx], 0, _val[_idx]);
}
_data = _b64.join('');
const _item = GenericUtils.base64ToString(_data);
return _item ? JSON.parse(_item) : null;
}
} |