@esfaenza/httpservice 11.2.32 → 11.2.36

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.
@@ -1,8 +1,8 @@
1
1
  (function (global, factory) {
2
- typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('@angular/common/http'), require('@angular/core'), require('rxjs/operators'), require('rxjs')) :
3
- typeof define === 'function' && define.amd ? define('@esfaenza/httpservice', ['exports', '@angular/common/http', '@angular/core', 'rxjs/operators', 'rxjs'], factory) :
4
- (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory((global.esfaenza = global.esfaenza || {}, global.esfaenza.httpservice = {}), global.ng.common.http, global.ng.core, global.rxjs.operators, global.rxjs));
5
- })(this, (function (exports, http, core, operators, rxjs) { 'use strict';
2
+ typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('@angular/common/http'), require('@angular/core'), require('@esfaenza/preferences'), require('rxjs/operators'), require('rxjs')) :
3
+ typeof define === 'function' && define.amd ? define('@esfaenza/httpservice', ['exports', '@angular/common/http', '@angular/core', '@esfaenza/preferences', 'rxjs/operators', 'rxjs'], factory) :
4
+ (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory((global.esfaenza = global.esfaenza || {}, global.esfaenza.httpservice = {}), global.ng.common.http, global.ng.core, global.preferences, global.rxjs.operators, global.rxjs));
5
+ })(this, (function (exports, http, core, preferences, operators, rxjs) { 'use strict';
6
6
 
7
7
  /*! *****************************************************************************
8
8
  Copyright (c) Microsoft Corporation.
@@ -444,9 +444,25 @@
444
444
  "Redirecting to Login, ignoring HTTP error on call": { "en-US": "Redirecting to Login, ignoring HTTP error on call", "it-IT": "Redireziono al login ignorando errori sulla chiamata", },
445
445
  "Already Handling an error, ignoring HTTP error on call": { "en-US": "Already Handling an error, ignoring HTTP error on call", "it-IT": "sto già gestendo un errore, ignoro quello corrente per la chiamata HTTP", },
446
446
  "Error 444 on call": { "en-US": "Error 444 on call", "it-IT": "Errore 444 su chiamata" },
447
- "Resource not found": { "en-US": "Resource not found", "it-IT": "Risorsa non trovata" }
447
+ "Resource not found": { "en-US": "Resource not found", "it-IT": "Risorsa non trovata" },
448
+ "Converted old storage system to new one": { "en-US": "Converted old storage system to new one", "it-IT": "Convertito il vecchio sistema di storicizzazione al nuovo" },
449
+ "Marking cache to be persisted as soon as possible": { "en-US": "Marking cache to be persisted as soon as possible", "it-IT": "Marco cache da persistere il prima possibile" },
450
+ "No more HTTP calls to be executed, entering idle state and persisting modified caches": { "en-US": "No more HTTP calls to be executed, entering idle state and persisting modified caches", "it-IT": "Nessun'altra chiamata HTTP dev'essere eseguita, entro in stato IDLE e persisto le cache modificate" },
451
+ "Caches succesfully persisted": { "en-US": "Caches succesfully persisted", "it-IT": "Le cache sono state persistite con successo" },
452
+ "Errors persisting modified caches": { "en-US": "Errors persisting modified caches", "it-IT": "Errori nella persistizione delle cache (esiste persistizione? boh...)" },
448
453
  };
449
454
 
455
+ var CacheInfos = /** @class */ (function () {
456
+ function CacheInfos(finalUrl, cache, cacheKey, cacheTime, cacheItem) {
457
+ this.finalUrl = finalUrl;
458
+ this.cache = cache;
459
+ this.cacheKey = cacheKey;
460
+ this.cacheTime = cacheTime;
461
+ this.cacheItem = cacheItem;
462
+ }
463
+ return CacheInfos;
464
+ }());
465
+
450
466
  /**
451
467
  * Servizio utilizzato per effettuare qualsiasi tipo di chiamata HTTP dall'applicazione, gestisce errori e cache delle risposte nativamente e ne può essere
452
468
  * esteso/modificato il comportamento implementando la classe di "hook" **IHttpServiceExtensions** e registrandola nel provider della classe **HttpServiceExtensions**
@@ -455,7 +471,7 @@
455
471
  /**
456
472
  * @ignore
457
473
  */
458
- function HTTPService(BACKEND_URL, EXTENSION_CLASS, HTTP_INVALIDATION, LOCALE, APP_NAME, CLIENT_CACHE_DURATION_S, CACHE_BY_USER, DEBUG_MODE, http) {
474
+ function HTTPService(BACKEND_URL, EXTENSION_CLASS, HTTP_INVALIDATION, LOCALE, APP_NAME, CLIENT_CACHE_DURATION_S, CACHE_BY_USER, DEBUG_MODE, http, localStorage) {
459
475
  var _a, _b;
460
476
  this.BACKEND_URL = BACKEND_URL;
461
477
  this.EXTENSION_CLASS = EXTENSION_CLASS;
@@ -466,34 +482,60 @@
466
482
  this.CACHE_BY_USER = CACHE_BY_USER;
467
483
  this.DEBUG_MODE = DEBUG_MODE;
468
484
  this.http = http;
469
- /**
470
- * Cache dello stato delle chiamate HTTP attualmente effettuate. Ogni chiamata è rappresentata da un GUID e lo status assume valore **false** solo sugli errori
471
- */
485
+ this.localStorage = localStorage;
486
+ /** Cache dello stato delle chiamate HTTP attualmente effettuate. Ogni chiamata è rappresentata da un GUID e lo status assume valore **false** solo sugli errori */
472
487
  this.callStatus = {};
473
- /**
474
- * Nome della cache in cui vengono storicizzate le informazioni sulle risposte delle chiamate sotto forma di dictionary
475
- */
488
+ /** Nome della cache in cui vengono storicizzate le informazioni sulle risposte delle chiamate sotto forma di dictionary */
476
489
  this.localStorageHttpCacheKey = null;
477
- /**
478
- * Nome della cache in cui vengono storicizzate le informazioni sulle risposte delle chiamate sotto forma di dictionary, solo per le chiamate con un tempo definito di caching
479
- */
490
+ /** Nome della cache in cui vengono storicizzate le informazioni sulle risposte delle chiamate sotto forma di dictionary, solo per le chiamate con un tempo definito di caching */
480
491
  this.localStorageHttpTimedCacheKey = null;
481
- /**
482
- * Nome della cache in cui vengono storicizzate le informazioni sullo scadere della cache stessa
483
- */
492
+ /** Nome della cache in cui vengono storicizzate le informazioni sullo scadere della cache stessa */
484
493
  this.localStorageHttpCacheExpireKey = null;
485
- /**
486
- * Identità collegata al token di autenticazione da usare, richiesta al programma che utilizza la libreria attraverso l'hook **retrieveIdentity** della **HttpServiceExtensions**
487
- */
494
+ /** Identità collegata al token di autenticazione da usare, richiesta al programma che utilizza la libreria attraverso l'hook **retrieveIdentity** della **HttpServiceExtensions** */
488
495
  this.me = null;
496
+ /** Indica che la cache a tempo dev'essere persistita il prima possibile */
497
+ this.PersistTimedCacheASAP = false;
498
+ /** Indica che la cache senza limiti di tempo dev'essere persistita il prima possibile */
499
+ this.PersistUntimedCacheASAP = false;
489
500
  this.ExtensionsImpl = this.EXTENSION_CLASS || new HttpServiceExtensions();
490
501
  this.me = this.ExtensionsImpl.retrieveIdentity();
491
502
  this.localStorageHttpCacheKey = ((_a = this.APP_NAME) !== null && _a !== void 0 ? _a : "APP").replace(/\s/g, '_') + "_HttpCache";
492
503
  this.localStorageHttpTimedCacheKey = ((_b = this.APP_NAME) !== null && _b !== void 0 ? _b : "APP").replace(/\s/g, '_') + "_HttpTimedCache";
493
504
  this.localStorageHttpCacheExpireKey = this.localStorageHttpCacheKey + "_Expire";
505
+ this.adjustOldStorageSystem();
494
506
  if (this.untimedCacheExpired())
495
507
  this.resetHttpUntimedCacheStorage();
496
508
  }
509
+ /**
510
+ * Se vedo che ci sono elementi salvati nel localStorage provo a toglierli e a risalvarli via preference.
511
+ * Nel caso migliore li sposto dal localStorage al DB di preference, nel caso peggiore li tolgo e li risalvo nel localStorage
512
+ */
513
+ HTTPService.prototype.adjustOldStorageSystem = function () {
514
+ return __awaiter(this, void 0, void 0, function () {
515
+ var lsTimed, lsUntimed;
516
+ return __generator(this, function (_e) {
517
+ switch (_e.label) {
518
+ case 0:
519
+ lsTimed = localStorage.getItem(this.localStorageHttpTimedCacheKey);
520
+ lsUntimed = localStorage.getItem(this.localStorageHttpCacheKey);
521
+ if (!lsTimed && !lsUntimed)
522
+ return [2 /*return*/];
523
+ localStorage.removeItem(this.localStorageHttpTimedCacheKey);
524
+ localStorage.removeItem(this.localStorageHttpCacheKey);
525
+ lsTimed = lsTimed ? JSON.parse(lsTimed) : {};
526
+ lsUntimed = lsUntimed ? JSON.parse(lsUntimed) : {};
527
+ return [4 /*yield*/, rxjs.forkJoin([
528
+ this.localStorage.setItem(this.localStorageHttpTimedCacheKey, lsTimed),
529
+ this.localStorage.setItem(this.localStorageHttpCacheKey, lsUntimed)
530
+ ]).toPromise()];
531
+ case 1:
532
+ _e.sent();
533
+ this.log(this.loc("Converted old storage system to new one"));
534
+ return [2 /*return*/];
535
+ }
536
+ });
537
+ });
538
+ };
497
539
  /**
498
540
  * Esecuzione di una GET HTTP con eventualmente la gestione della cache qualora la chiamata termini con la convenzione "#cache"
499
541
  *
@@ -530,7 +572,7 @@
530
572
  if (errorCallback)
531
573
  errorCallback();
532
574
  return !succesfulResultMandatory ? rxjs.throwError(err) : _this.registerErrorAndReturnEmptyObservable(err, myGuid);
533
- }), operators.finalize(function () { _this.tryFinalizeByGuid(myGuid); }));
575
+ }), operators.finalize(function () { _this.tryFinalizeByGuid(myGuid, cachedInfos); }));
534
576
  };
535
577
  /**
536
578
  * Esecuzione di una GET HTTP con eventualmente la gestione della cache qualora la chiamata termini con la convenzione "#cache"
@@ -571,7 +613,7 @@
571
613
  if (errorCallback)
572
614
  errorCallback();
573
615
  return !succesfulResultMandatory ? rxjs.throwError(err) : _this.registerErrorAndReturnEmptyObservable(err, myGuid);
574
- }), operators.finalize(function () { _this.tryFinalizeByGuid(myGuid); }));
616
+ }), operators.finalize(function () { _this.tryFinalizeByGuid(myGuid, cachedInfos); }));
575
617
  };
576
618
  /**
577
619
  * Esecuzione di una POST HTTP
@@ -810,7 +852,7 @@
810
852
  */
811
853
  HTTPService.prototype.checkCacheInvalidation = function (url) {
812
854
  var _this = this;
813
- var cache = JSON.parse(localStorage.getItem(this.localStorageHttpCacheKey));
855
+ var cache = this.localStorage.getLocalItem(this.localStorageHttpCacheKey);
814
856
  var tmp = /#cache(:?-(\d+))/gi.exec(url);
815
857
  var cacheTime = tmp ? tmp[2] : null;
816
858
  var normalizedUrl = url.replace("#cache" + (cacheTime ? "-" + cacheTime : ""), "").replace(this.BACKEND_URL, "");
@@ -831,21 +873,60 @@
831
873
  this.log(this.loc("Invlalidating cache element") + " " + k);
832
874
  delete cache[k];
833
875
  }
834
- localStorage.setItem(this.localStorageHttpCacheKey, JSON.stringify(cache));
876
+ this.localStorage.setLocalItem(this.localStorageHttpCacheKey, cache);
835
877
  };
836
878
  /**
837
879
  * Finalizzazione di una chiamata
838
880
  *
839
881
  * @param {string} guid GUID collegato alla chiamata appena terminata
882
+ * @param {boolean} persistCacheIfIdle Effettua il persist della cache HTTP solo se non ci sono altre chiamate in corso, per evitare
883
+ * che mi cambi sotto l'oggetto di cache mentre sto salvando le informazioni
840
884
  */
841
- HTTPService.prototype.tryFinalizeByGuid = function (guid) {
842
- this.log(this.loc("Finalizing call") + " " + guid + " " + this.loc("with status") + ": " + (this.callStatus[guid] ? this.loc('Success') : this.loc('Failure')));
843
- //Alla prima chiamata buona, significa che almeno il login ce l'ho. Posso mettermi in modalità redirectInProgress false
844
- //e riiniziare a valutare errori di javashit
845
- if (this.callStatus[guid] && this.ExtensionsImpl.readRedirectionStatus())
846
- this.ExtensionsImpl.writeRedirectionStatus(false);
847
- //In ogni caso questa posso rimuoverla
848
- delete this.callStatus[guid];
885
+ HTTPService.prototype.tryFinalizeByGuid = function (guid, cacheInfos) {
886
+ return __awaiter(this, void 0, void 0, function () {
887
+ var toCall, tmpKey, ret;
888
+ return __generator(this, function (_e) {
889
+ switch (_e.label) {
890
+ case 0:
891
+ this.log(this.loc("Finalizing call") + " " + guid + " " + this.loc("with status") + ": " + (this.callStatus[guid] ? this.loc('Success') : this.loc('Failure')));
892
+ //Alla prima chiamata buona, significa che almeno il login ce l'ho. Posso mettermi in modalità redirectInProgress false
893
+ //e riiniziare a valutare errori di javashit
894
+ if (this.callStatus[guid] && this.ExtensionsImpl.readRedirectionStatus())
895
+ this.ExtensionsImpl.writeRedirectionStatus(false);
896
+ //In ogni caso questa posso rimuoverla
897
+ delete this.callStatus[guid];
898
+ // Se vengo da una chiamata che ha aggiornato la cache a timer o globale marco il fatto che quella cache dev'essere aggiornata
899
+ if (cacheInfos && cacheInfos.cache) {
900
+ this.PersistTimedCacheASAP = this.PersistTimedCacheASAP || !!cacheInfos.cacheTime;
901
+ this.PersistUntimedCacheASAP = this.PersistTimedCacheASAP || !cacheInfos.cacheTime;
902
+ this.log(this.loc("Marking cache to be persisted as soon as possible"));
903
+ }
904
+ if (!((this.PersistTimedCacheASAP || this.PersistUntimedCacheASAP) && Object.keys(this.callStatus).length == 0)) return [3 /*break*/, 2];
905
+ toCall = [];
906
+ tmpKey = "";
907
+ if (this.PersistTimedCacheASAP) {
908
+ tmpKey = this.localStorageHttpTimedCacheKey;
909
+ toCall.push(this.localStorage.setItem(tmpKey, this.localStorage.getLocalItem(tmpKey)));
910
+ }
911
+ if (this.PersistUntimedCacheASAP) {
912
+ tmpKey = this.localStorageHttpCacheKey;
913
+ toCall.push(this.localStorage.setItem(tmpKey, this.localStorage.getLocalItem(tmpKey)));
914
+ }
915
+ this.log(this.loc("No more HTTP calls to be executed, entering idle state and persisting modified caches") + "...");
916
+ return [4 /*yield*/, rxjs.forkJoin(toCall).toPromise()];
917
+ case 1:
918
+ ret = _e.sent();
919
+ if (ret)
920
+ this.log(this.loc("Caches succesfully persisted"));
921
+ else
922
+ this.log(this.loc("Errors persisting modified caches"));
923
+ this.PersistTimedCacheASAP = false;
924
+ this.PersistUntimedCacheASAP = false;
925
+ _e.label = 2;
926
+ case 2: return [2 /*return*/];
927
+ }
928
+ });
929
+ });
849
930
  };
850
931
  /**
851
932
  * Helper che dato un unico File o una lista di File crea un oggetto FormData che può essere inviato comodamente
@@ -891,7 +972,7 @@
891
972
  if (authtoken && includeAuth)
892
973
  headers = headers.append("Authorization", "Bearer " + authtoken);
893
974
  if (accept)
894
- headers = headers.append("Accept", "application/json");
975
+ headers = headers.append("Accept", accept);
895
976
  headers = headers.append("Accept-Language", (_a = this.LOCALE) !== null && _a !== void 0 ? _a : 'it-IT');
896
977
  return headers;
897
978
  };
@@ -1049,7 +1130,7 @@
1049
1130
  * @param {string} url URL su cui effettuare la chiamata
1050
1131
  * @param {HttpParams} params Parametri della chiamata (nulli in caso di POST)
1051
1132
  *
1052
- * @returns {{ finalUrl: string, cache: boolean, cacheKey: string, cacheTime: string, cacheItem: any }} Oggetto contenente le informazioni sulla cache per l'oggetto specificato
1133
+ * @returns {CacheInfos} Oggetto contenente le informazioni sulla cache per l'oggetto specificato
1053
1134
  */
1054
1135
  HTTPService.prototype.tryGetCacheInformations = function (url, params) {
1055
1136
  var cachingKey = null, cacheTime = null, cache = null, item = null;
@@ -1062,8 +1143,8 @@
1062
1143
  this.resetHttpUntimedCacheStorage();
1063
1144
  cachingKey = this.makeCacheKey(url, params);
1064
1145
  var cacheKey = cacheTime ? this.localStorageHttpTimedCacheKey : this.localStorageHttpCacheKey;
1065
- var cacheLs = localStorage.getItem(cacheKey);
1066
- var cache_1 = cacheLs ? JSON.parse(cacheLs) : {};
1146
+ var cacheLs = this.localStorage.getLocalItem(cacheKey);
1147
+ var cache_1 = cacheLs ? cacheLs : {};
1067
1148
  if (cache_1 && cache_1[cachingKey] && !this.timedCacheItemExpired(cache_1[cachingKey])) {
1068
1149
  // Se gestisco il tempo esatto della cache prima di restituire l'oggetto cachato lo ripulisco
1069
1150
  // dalle proprietà interne che gli ho aggiunto per controllarne la scadenza
@@ -1072,22 +1153,22 @@
1072
1153
  item = cache_1[cachingKey];
1073
1154
  }
1074
1155
  }
1075
- return { finalUrl: url, cache: useCaching, cacheKey: cachingKey, cacheTime: cacheTime, cacheItem: item };
1156
+ return new CacheInfos(url, useCaching, cachingKey, cacheTime, item);
1076
1157
  };
1077
1158
  /**
1078
1159
  * Inserisce un oggetto nella cache appropriata in base alle informazioni contenute nel parametro **cacheInfos**
1079
1160
  *
1080
1161
  * @param {T} item Oggetto da inserire nella cache
1081
- * @param {{ finalUrl: string, cache: boolean, cacheKey: string, cacheTime: string, cacheItem: any }} cacheInfos Informazioni sulla cache recuperate da una chiamata precedente a **tryGetCacheInformations**
1162
+ * @param {CacheInfos} cacheInfos Informazioni sulla cache recuperate da una chiamata precedente a **tryGetCacheInformations**
1082
1163
  */
1083
1164
  HTTPService.prototype.cacheResponse = function (item, cacheInfos) {
1084
1165
  var cacheKey = cacheInfos.cacheTime ? this.localStorageHttpTimedCacheKey : this.localStorageHttpCacheKey;
1085
- var cacheLs = localStorage.getItem(cacheKey);
1086
- var cache = cacheLs ? JSON.parse(cacheLs) : {};
1166
+ var cacheLs = this.localStorage.getLocalItem(cacheKey);
1167
+ var cache = cacheLs ? cacheLs : {};
1087
1168
  cache[cacheInfos.cacheKey] = item;
1088
1169
  if (cacheInfos.cacheTime)
1089
1170
  cache[cacheInfos.cacheKey].__expire = dayjs().add(cacheInfos.cacheTime, "seconds");
1090
- localStorage.setItem(cacheKey, JSON.stringify(cache));
1171
+ this.localStorage.setLocalItem(cacheKey, cache);
1091
1172
  };
1092
1173
  /**
1093
1174
  * Controlla se la cache per le chiamate senza expire time è scaduta
@@ -1113,14 +1194,14 @@
1113
1194
  */
1114
1195
  HTTPService.prototype.resetHttpUntimedCacheStorage = function () {
1115
1196
  var _a;
1116
- localStorage.setItem(this.localStorageHttpCacheKey, JSON.stringify({}));
1197
+ this.localStorage.setItem(this.localStorageHttpCacheKey, {}).subscribe();
1117
1198
  localStorage.setItem(this.localStorageHttpCacheExpireKey, JSON.stringify(dayjs().add((_a = this.CLIENT_CACHE_DURATION_S) !== null && _a !== void 0 ? _a : 3600, "second")));
1118
1199
  };
1119
1200
  /**
1120
1201
  * Ripulisce la cache delle chiamate con un tempo di expire definito
1121
1202
  */
1122
1203
  HTTPService.prototype.resetHttpTimedCacheStorage = function () {
1123
- localStorage.setItem(this.localStorageHttpTimedCacheKey, JSON.stringify({}));
1204
+ this.localStorage.setItem(this.localStorageHttpTimedCacheKey, {});
1124
1205
  };
1125
1206
  /**
1126
1207
  * Genera una chiave per la cache delle chiamate in base ad URL e Parametri HTTP
@@ -1132,8 +1213,8 @@
1132
1213
  */
1133
1214
  HTTPService.prototype.makeCacheKey = function (url, params) {
1134
1215
  var authKeyPart = (this.me ? this.me.Idtenant : "") + (this.me && this.CACHE_BY_USER ? this.me.IdUser : "");
1135
- var paramsKeyPart = params && params.keys().length > 0 ? params.keys().reduce(function (prev, next) { return prev + next + '=' + params.get(next); }, "") : "";
1136
- return authKeyPart + url + paramsKeyPart;
1216
+ var paramsKeyPart = params && params.keys().length > 0 ? params.keys().reduce(function (prev, next) { return prev + "," + next + '=' + params.get(next); }, "") : "";
1217
+ return authKeyPart + "_" + url.substring(url.indexOf("api") + 4) + "?" + paramsKeyPart;
1137
1218
  };
1138
1219
  /**
1139
1220
  * Generazione GUID
@@ -1183,7 +1264,8 @@
1183
1264
  { type: undefined, decorators: [{ type: core.Optional }, { type: core.Inject, args: [CLIENT_CACHE_DURATION_S,] }] },
1184
1265
  { type: Boolean, decorators: [{ type: core.Optional }, { type: core.Inject, args: [CACHE_BY_USER,] }] },
1185
1266
  { type: Boolean, decorators: [{ type: core.Optional }, { type: core.Inject, args: [DEBUG_MODE,] }] },
1186
- { type: http.HttpClient }
1267
+ { type: http.HttpClient },
1268
+ { type: preferences.PreferencesService }
1187
1269
  ]; };
1188
1270
 
1189
1271
  var HttpserviceModule = /** @class */ (function () {