@esfaenza/httpservice 12.2.22 → 13.1.0

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.
Files changed (25) hide show
  1. package/esfaenza-httpservice.d.ts +1 -1
  2. package/esm2020/esfaenza-httpservice.mjs +5 -0
  3. package/{esm2015/lib/config/HttpServiceExtensions.js → esm2020/lib/config/HttpServiceExtensions.mjs} +0 -0
  4. package/{esm2015/lib/config/HttpServiceModuleConfig.js → esm2020/lib/config/HttpServiceModuleConfig.mjs} +0 -0
  5. package/{esm2015/lib/config/IHttpServiceExtensions.js → esm2020/lib/config/IHttpServiceExtensions.mjs} +0 -0
  6. package/esm2020/lib/httpservice.module.mjs +30 -0
  7. package/{esm2015/lib/httpservice.service.loc.js → esm2020/lib/httpservice.service.loc.mjs} +0 -0
  8. package/esm2020/lib/httpservice.service.mjs +716 -0
  9. package/{esm2015/lib/models/Download.js → esm2020/lib/models/Download.mjs} +0 -0
  10. package/{esm2015/lib/tokens.js → esm2020/lib/tokens.mjs} +0 -0
  11. package/{esm2015/public-api.js → esm2020/public-api.mjs} +0 -0
  12. package/fesm2015/{esfaenza-httpservice.js → esfaenza-httpservice.mjs} +51 -20
  13. package/fesm2015/esfaenza-httpservice.mjs.map +1 -0
  14. package/fesm2020/esfaenza-httpservice.mjs +885 -0
  15. package/fesm2020/esfaenza-httpservice.mjs.map +1 -0
  16. package/lib/httpservice.module.d.ts +4 -0
  17. package/lib/httpservice.service.d.ts +3 -0
  18. package/package.json +21 -9
  19. package/bundles/esfaenza-httpservice.umd.js +0 -1253
  20. package/bundles/esfaenza-httpservice.umd.js.map +0 -1
  21. package/esfaenza-httpservice.metadata.json +0 -1
  22. package/esm2015/esfaenza-httpservice.js +0 -6
  23. package/esm2015/lib/httpservice.module.js +0 -26
  24. package/esm2015/lib/httpservice.service.js +0 -698
  25. package/fesm2015/esfaenza-httpservice.js.map +0 -1
@@ -0,0 +1,885 @@
1
+ import * as i2 from '@angular/common/http';
2
+ import { HttpEventType, HttpHeaders, HttpErrorResponse } from '@angular/common/http';
3
+ import * as i0 from '@angular/core';
4
+ import { InjectionToken, Injectable, Inject, Optional, NgModule } from '@angular/core';
5
+ import { delay, finalize, map, catchError, scan } from 'rxjs/operators';
6
+ import { of, throwError, Observable } from 'rxjs';
7
+
8
+ /**
9
+ * Dizionario di invalidazioni delle chiamate HTTP
10
+ */
11
+ const HTTP_INVALIDATION = new InjectionToken('HTTP_INVALIDATION');
12
+ /**
13
+ * Durata della cache lato libreria dopo il quale la cache verrà ripulita
14
+ */
15
+ const CLIENT_CACHE_DURATION_S = new InjectionToken('CLIENT_CACHE_DURATION_S');
16
+ /**
17
+ * URL del Backend a cui inviare le chiamate
18
+ */
19
+ const BACKEND_URL = new InjectionToken('BACKEND_URL');
20
+ /**
21
+ * Locale della libreria per messaggi d'errore ed Header di default "Accept-Language". Sono supportati "it-IT" ed "en-US"
22
+ */
23
+ const HTTP_LOCALE = new InjectionToken('HTTP_LOCALE');
24
+ /**
25
+ * Nome dell'APP utilizzato per creare le chiavi delle cache specifiche per l'applicazione corrente
26
+ */
27
+ const APP_NAME = new InjectionToken('APP_NAME');
28
+ /**
29
+ * Indica se utilizzare l'identificativo utente nella cache
30
+ */
31
+ const CACHE_BY_USER = new InjectionToken('CACHE_BY_USER');
32
+ /**
33
+ * Indica se fare log nella console ad ogni azione significativa
34
+ */
35
+ const DEBUG_MODE = new InjectionToken('DEBUG_MODE');
36
+
37
+ /**
38
+ * Classe d'estensione che permette di modificare il comportamento della libreria negli hook definiti da interfaccia, in modo da poterla adattare
39
+ * con un certo grado di customizzazione a qualsiasi struttura di frontend
40
+ */
41
+ class HttpServiceExtensions {
42
+ /**
43
+ * Hook per recuperare l'access token con cui effettuare le chiamate HTTP
44
+ */
45
+ retrieveAccessToken() {
46
+ return "";
47
+ }
48
+ /**
49
+ * Hook per recuperare l'Identity corrente in un oggetto generico con le informazioni di User e Tenant
50
+ */
51
+ retrieveIdentity() {
52
+ return null;
53
+ }
54
+ /**
55
+ * Hook per leggere dallo stato dell'applicazione se stiamo già venendo ridirezionati al login, in modo da non tentare di effettuare
56
+ * N redirect contemporaneamente qualora molte API fallissero allo stesso tempo nell'autenticazione
57
+ */
58
+ readRedirectingToLogin() {
59
+ return false;
60
+ }
61
+ /**
62
+ * Hook per scrivere nello stato dell'applicazione se stiamo effettuando un redirect al login o meno
63
+ */
64
+ writeRedirectingToLogin(status) {
65
+ }
66
+ /**
67
+ * Hook per effettuare il redirect al login
68
+ */
69
+ redirectToLogin() {
70
+ }
71
+ /**
72
+ * Hook per leggere dallo stato dell'applicazione se stiamo già gestendo un errore, in modo da non tentare di gestire
73
+ * N errori contemporaneamente qualora molte API fallissero allo stesso tempo
74
+ */
75
+ readHandlingErrorStatus() {
76
+ return false;
77
+ }
78
+ /**
79
+ * Hook per scrivere nello stato dell'applicazione se stiamo gestendo un errore o meno
80
+ */
81
+ writeHandlingErrorStatus(status) {
82
+ }
83
+ /**
84
+ * Hook per leggere dallo stato dell'applicazione se stiamo già gestendo un redirect, in modo da non tentare di gestire
85
+ * N redirect contemporaneamente qualora molte API lo richiedessero allo stesso tempo
86
+ */
87
+ readRedirectionStatus() {
88
+ return false;
89
+ }
90
+ /**
91
+ * Hook per scrivere nello stato dell'applicazione se stiamo gestendo un redirect o meno
92
+ */
93
+ writeRedirectionStatus(status) {
94
+ }
95
+ /**
96
+ * Hook per indicare se l'applicazione può gestire eccezioni del tipo "NotConfigured" (444). Qualora l'applicazione che lo implementa dichiari di gestirle verrà chiamata
97
+ * la funzione **handleBlockingException** per ognuno di questi errori
98
+ */
99
+ handleNotConfiguredException() {
100
+ return false;
101
+ }
102
+ /**
103
+ * Hook per la gestione di un qualsiasi errore bloccante per l'operazione attuale, ma non fatale (Generalmente gestibile da dialog di avviso)
104
+ */
105
+ handleBlockingException(status, text) {
106
+ console.error("ESHttpError Blocking Exception " + status + " " + text);
107
+ }
108
+ /**
109
+ * Hook per la gestione di un qualsiasi errore fatale (Generalmente gestibile tramite navigazione a una pagina di errore custom per l'applicativo)
110
+ */
111
+ handleException(status, text) {
112
+ console.error("ESHttpError " + status + " " + text);
113
+ }
114
+ }
115
+
116
+ /**
117
+ * Oggetto statico di localizzazione per i messaggi
118
+ */
119
+ const Loc = {
120
+ "Result for": { "en-US": "Result for", "it-IT": "Risultato per", },
121
+ "retrieved from cache": { "en-US": "retrieved from cache", "it-IT": "recuperato dalla cache", },
122
+ "Cached result for": { "en-US": "Cached result for", "it-IT": "Messo in cache risultato per", },
123
+ "Starting call": { "en-US": "Starting call", "it-IT": "Inizio la chiamata", },
124
+ "at URL": { "en-US": "at URL", "it-IT": "all'URL", },
125
+ "Invlalidating cache element": { "en-US": "Invlalidating cache element", "it-IT": "Invalido elemento della cache", },
126
+ "Finalizing call": { "en-US": "Finalizing call", "it-IT": "Finalizzo chiamata", },
127
+ "with status": { "en-US": "with status", "it-IT": "con stato", },
128
+ "Success": { "en-US": "Success", "it-IT": "Successso", },
129
+ "Failure": { "en-US": "Failure", "it-IT": "Fallimento", },
130
+ "Error 401 on call": { "en-US": "Error 401 on call", "it-IT": "Errore 401 su chiamata", },
131
+ "with redirect already in progress. Ignoring this event": { "en-US": "with redirect already in progress. Ignoring this event", "it-IT": "con redirezione già in corso. Ignoro l'evento", },
132
+ "redirecting to login": { "en-US": "redirecting to login", "it-IT": "redireziono al login", },
133
+ "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", },
134
+ "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", },
135
+ "Error 444 on call": { "en-US": "Error 444 on call", "it-IT": "Errore 444 su chiamata" },
136
+ "Resource not found": { "en-US": "Resource not found", "it-IT": "Risorsa non trovata" }
137
+ };
138
+
139
+ // Angular
140
+ /**
141
+ * Servizio utilizzato per effettuare qualsiasi tipo di chiamata HTTP dall'applicazione, gestisce errori e cache delle risposte nativamente e ne può essere
142
+ * esteso/modificato il comportamento implementando la classe di "hook" **IHttpServiceExtensions** e registrandola nel provider della classe **HttpServiceExtensions**
143
+ */
144
+ class HTTPService {
145
+ /**
146
+ * @ignore
147
+ */
148
+ constructor(BACKEND_URL, EXTENSION_CLASS, HTTP_INVALIDATION, LOCALE, APP_NAME, CLIENT_CACHE_DURATION_S, CACHE_BY_USER, DEBUG_MODE, http) {
149
+ this.BACKEND_URL = BACKEND_URL;
150
+ this.EXTENSION_CLASS = EXTENSION_CLASS;
151
+ this.HTTP_INVALIDATION = HTTP_INVALIDATION;
152
+ this.LOCALE = LOCALE;
153
+ this.APP_NAME = APP_NAME;
154
+ this.CLIENT_CACHE_DURATION_S = CLIENT_CACHE_DURATION_S;
155
+ this.CACHE_BY_USER = CACHE_BY_USER;
156
+ this.DEBUG_MODE = DEBUG_MODE;
157
+ this.http = http;
158
+ /**
159
+ * Cache dello stato delle chiamate HTTP attualmente effettuate. Ogni chiamata è rappresentata da un GUID e lo status assume valore **false** solo sugli errori
160
+ */
161
+ this.callStatus = {};
162
+ /**
163
+ * Nome della cache in cui vengono storicizzate le informazioni sulle risposte delle chiamate sotto forma di dictionary
164
+ */
165
+ this.localStorageHttpCacheKey = null;
166
+ /**
167
+ * 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
168
+ */
169
+ this.localStorageHttpTimedCacheKey = null;
170
+ /**
171
+ * Nome della cache in cui vengono storicizzate le informazioni sullo scadere della cache stessa
172
+ */
173
+ this.localStorageHttpCacheExpireKey = null;
174
+ /**
175
+ * Identità collegata al token di autenticazione da usare, richiesta al programma che utilizza la libreria attraverso l'hook **retrieveIdentity** della **HttpServiceExtensions**
176
+ */
177
+ this.me = null;
178
+ this.ExtensionsImpl = this.EXTENSION_CLASS || new HttpServiceExtensions();
179
+ this.me = this.ExtensionsImpl.retrieveIdentity();
180
+ this.localStorageHttpCacheKey = (this.APP_NAME ?? "APP").replace(/\s/g, '_') + "_HttpCache";
181
+ this.localStorageHttpTimedCacheKey = (this.APP_NAME ?? "APP").replace(/\s/g, '_') + "_HttpTimedCache";
182
+ this.localStorageHttpCacheExpireKey = this.localStorageHttpCacheKey + "_Expire";
183
+ if (this.untimedCacheExpired())
184
+ this.resetHttpUntimedCacheStorage();
185
+ }
186
+ /**
187
+ * Esecuzione di una GET HTTP con eventualmente la gestione della cache qualora la chiamata termini con la convenzione "#cache"
188
+ *
189
+ * @param {string} url URL su cui effettuare la chiamata
190
+ * @param {HttpParams} params Parametri della chiamata
191
+ * @param {string} transaction Codice transazione collegato a questa chiamata. Viene inserito nell'Header "X-TX-ID" e lato Backend dovrà essere gestito di conseguenza
192
+ * @param {boolean} succesfulResultMandatory Indica che questa chiamata deve assolutamente andare bene. In caso contrario viene fisicamente fatto il throw che può essere
193
+ * raccolto da chi usa la libreria nella pipe "onError" dell'Observable restituito ed essere gestito in maniera non standard
194
+ * @param {Function} errorCallback Callback chiamato in caso di errore
195
+ *
196
+ * @returns {Observable<T>} Observable che contiene il risultato della chiamata
197
+ */
198
+ get(url, params = null, transaction = "", succesfulResultMandatory = true, errorCallback = null) {
199
+ let myGuid = this.defaultStartCall(url);
200
+ let cachedInfos = this.tryGetCacheInformations(url, params);
201
+ if (cachedInfos.cache && cachedInfos.cacheItem) {
202
+ this.log(this.loc("Result for") + " " + url + " " + this.loc("retrieved from cache"));
203
+ return of(cachedInfos.cacheItem).pipe(delay(0), finalize(() => { this.tryFinalizeByGuid(myGuid); }));
204
+ }
205
+ var httpCall = this.http.get(cachedInfos.finalUrl, { headers: this.getHeaders(transaction), params: params });
206
+ return httpCall.pipe(map((res) => {
207
+ let responseItem = res;
208
+ if (cachedInfos.cache) {
209
+ this.cacheResponse(responseItem, cachedInfos);
210
+ this.log(this.loc("Cached result for") + " " + url);
211
+ }
212
+ return responseItem;
213
+ }), catchError((err, caught) => {
214
+ if (errorCallback)
215
+ errorCallback();
216
+ return !succesfulResultMandatory ? throwError(err) : this.registerErrorAndReturnEmptyObservable(err, myGuid);
217
+ }), finalize(() => { this.tryFinalizeByGuid(myGuid); }));
218
+ }
219
+ /**
220
+ * Esecuzione di una GET HTTP con eventualmente la gestione della cache qualora la chiamata termini con la convenzione "#cache"
221
+ *
222
+ * Caso specifico di chiamata che deve restituire un Blob o un ArrayBuffer nativo da elaborare
223
+ *
224
+ * @param {string} url URL su cui effettuare la chiamata
225
+ * @param {HttpParams} params Parametri della chiamata
226
+ * @param {"arraybuffer"| "blob"} type Tipo di ritorno richiesto
227
+ * @param {string} transaction Codice transazione collegato a questa chiamata. Viene inserito nell'Header "X-TX-ID" e lato Backend dovrà essere gestito di conseguenza
228
+ * @param {boolean} succesfulResultMandatory Indica che questa chiamata deve assolutamente andare bene. In caso contrario viene fisicamente fatto il throw che può essere
229
+ * raccolto da chi usa la libreria nella pipe "onError" dell'Observable restituito ed essere gestito in maniera non standard
230
+ * @param {Function} errorCallback Callback chiamato in caso di errore
231
+ *
232
+ * @returns {Observable<Blob | ArrayBuffer>} Observable che contiene il risultato della chiamata
233
+ */
234
+ getRaw(url, params = null, type = "arraybuffer", transaction = "", succesfulResultMandatory = true, errorCallback = null) {
235
+ let myGuid = this.defaultStartCall(url);
236
+ let cachedInfos = this.tryGetCacheInformations(url, params);
237
+ if (cachedInfos.cache && cachedInfos.cacheItem) {
238
+ this.log(this.loc("Result for") + " " + url + " " + this.loc("retrieved from cache"));
239
+ return of(cachedInfos.cacheItem).pipe(delay(0), finalize(() => { this.tryFinalizeByGuid(myGuid); }));
240
+ }
241
+ var httpCall = this.http.get(cachedInfos.finalUrl, { responseType: type, headers: this.getHeaders(transaction), params: params });
242
+ return httpCall.pipe(map((blob) => {
243
+ if (cachedInfos.cache) {
244
+ this.cacheResponse(blob, cachedInfos);
245
+ this.log(this.loc("Cached result for") + " " + url);
246
+ }
247
+ return blob;
248
+ }), catchError((err, caught) => {
249
+ if (errorCallback)
250
+ errorCallback();
251
+ return !succesfulResultMandatory ? throwError(err) : this.registerErrorAndReturnEmptyObservable(err, myGuid);
252
+ }), finalize(() => { this.tryFinalizeByGuid(myGuid); }));
253
+ }
254
+ /**
255
+ * Esecuzione di una POST HTTP
256
+ *
257
+ * @param {string} url URL su cui effettuare la chiamata
258
+ * @param {any} bodyData DTO per la chiamata
259
+ * @param {HttpParams} params Parametri della chiamata
260
+ * @param {string} transaction Codice transazione collegato a questa chiamata. Viene inserito nell'Header "X-TX-ID" e lato Backend dovrà essere gestito di conseguenza
261
+ * @param {boolean} succesfulResultMandatory Indica che questa chiamata deve assolutamente andare bene. In caso contrario viene fisicamente fatto il throw che può essere
262
+ * raccolto da chi usa la libreria nella pipe "onError" dell'Observable restituito ed essere gestito in maniera non standard
263
+ *
264
+ * @returns {Observable<T>} Observable che contiene il risultato della chiamata
265
+ */
266
+ post(url, bodyData, params = null, transaction = "", succesfulResultMandatory = true) {
267
+ let myGuid = this.defaultStartCall(url);
268
+ var httpCall = this.http.post(url, bodyData, { headers: this.getHeaders(transaction), params: params });
269
+ return httpCall.pipe(map((res) => {
270
+ let responseItem = res;
271
+ return responseItem;
272
+ }), catchError((err, caught) => {
273
+ return !succesfulResultMandatory ? throwError(err) : this.registerErrorAndReturnEmptyObservable(err, myGuid);
274
+ }), finalize(() => { this.tryFinalizeByGuid(myGuid); }));
275
+ }
276
+ /**
277
+ * Esecuzione di una DELETE HTTP
278
+ *
279
+ * @param {string} url URL su cui effettuare la chiamata
280
+ * @param {HttpParams} params Parametri della chiamata
281
+ * @param {string} transaction Codice transazione collegato a questa chiamata. Viene inserito nell'Header "X-TX-ID" e lato Backend dovrà essere gestito di conseguenza
282
+ * @param {boolean} succesfulResultMandatory Indica che questa chiamata deve assolutamente andare bene. In caso contrario viene fisicamente fatto il throw che può essere
283
+ * raccolto da chi usa la libreria nella pipe "onError" dell'Observable restituito ed essere gestito in maniera non standard
284
+ *
285
+ * @returns {Observable<T>} Observable che contiene il risultato della chiamata
286
+ */
287
+ delete(url, params = null, transaction = "", succesfulResultMandatory = true) {
288
+ let myGuid = this.defaultStartCall(url);
289
+ var httpCall = this.http.delete(url, { headers: this.getHeaders(transaction), params: params });
290
+ return httpCall.pipe(map((res) => {
291
+ let responseItem = res;
292
+ return responseItem;
293
+ }), catchError((err, caught) => {
294
+ return !succesfulResultMandatory ? throwError(err) : this.registerErrorAndReturnEmptyObservable(err, myGuid);
295
+ }), finalize(() => { this.tryFinalizeByGuid(myGuid); }));
296
+ }
297
+ /**
298
+ * Esecuzione di una PUT HTTP
299
+ *
300
+ * @param {string} url URL su cui effettuare la chiamata
301
+ * @param {any} bodyData DTO per la chiamata
302
+ * @param {HttpParams} params Parametri della chiamata
303
+ * @param {string} transaction Codice transazione collegato a questa chiamata. Viene inserito nell'Header "X-TX-ID" e lato Backend dovrà essere gestito di conseguenza
304
+ * @param {boolean} succesfulResultMandatory Indica che questa chiamata deve assolutamente andare bene. In caso contrario viene fisicamente fatto il throw che può essere
305
+ * raccolto da chi usa la libreria nella pipe "onError" dell'Observable restituito ed essere gestito in maniera non standard
306
+ *
307
+ * @returns {Observable<T>} Observable che contiene il risultato della chiamata
308
+ */
309
+ put(url, bodyData, params = null, transaction = "", succesfulResultMandatory = true) {
310
+ let myGuid = this.defaultStartCall(url);
311
+ var httpCall = this.http.put(url, bodyData, { headers: this.getHeaders(transaction), params: params });
312
+ return httpCall.pipe(map((res) => {
313
+ let responseItem = res;
314
+ return responseItem;
315
+ }), catchError((err, caught) => {
316
+ return !succesfulResultMandatory ? throwError(err) : this.registerErrorAndReturnEmptyObservable(err, myGuid);
317
+ }), finalize(() => { this.tryFinalizeByGuid(myGuid); }));
318
+ }
319
+ /**
320
+ * Esecuzione di una POST HTTP
321
+ *
322
+ * Casistica particolare in cui bisogna anche inviare dei File
323
+ *
324
+ * @param {string} url URL su cui effettuare la chiamata
325
+ * @param {any} bodyData DTO per la chiamata
326
+ * @param {File[] | File} fileArrayOrFile Singolo file o lista di file da inviare. Il tipo **File** è quello nativo del Javascript
327
+ *
328
+ * @returns {Observable<T>} Observable che contiene il risultato della chiamata
329
+ */
330
+ postwithFiles(url, bodyData, fileArrayOrFile) {
331
+ let myGuid = this.defaultStartCall(url);
332
+ var formData = this.getFilesFormData(fileArrayOrFile);
333
+ formData.append("body", JSON.stringify(bodyData));
334
+ var httpCall = this.http.post(url, formData, { headers: this.getHeaders(null, true, null, null) });
335
+ return httpCall.pipe(catchError((err, caught) => { return this.registerErrorAndReturnEmptyObservable(err, myGuid); }), finalize(() => { this.tryFinalizeByGuid(myGuid); }));
336
+ }
337
+ /**
338
+ * Esecuzione di una POST HTTP
339
+ *
340
+ * Casistica particolare in cui viene restituito un file gestito come ObjectURL il cui URL si può gestire dal parametro di callback **getFileCallback**.
341
+ * La chiamata non ha un tipo restituito in quanto il risultato dev'essere gestito attraverso la callback **getFileCallback**
342
+ *
343
+ * @param {string} url URL su cui effettuare la chiamata
344
+ * @param {K} bodyData DTO per la chiamata
345
+ * @param {string} filename Nome del file che si sta richiedendo, rimane lato Frontend e serve per assegnare arbitrariamente un nome al file restituito, se vuoto viene utilizzata la Content-Disposition della risposta
346
+ * @param {Function} getFileCallback Callback a due parametri (url: string, filename: string) per gestire il risultato del file richiesto. **Utilizzare UtilityService.fileDownload** di @esfaenza/extensions
347
+ * @param {Function} afterGetFile Callback da chiamare dopo aver gestito la risposta del **getFileCallback**, in caso **handleError** fosse **false** verrà richiamato anche in caso di errore
348
+ * @param {boolean} handleError Indica se di default gli errori devono essere gestiti dalla libreria o se devono essere ignorati
349
+ */
350
+ postGetFile(url, bodyData, filename, getFileCallback, afterGetFile = null, handleError = true) {
351
+ let myGuid = this.defaultStartCall(url);
352
+ this.http.post(url, bodyData, { headers: this.getHeaders(), observe: 'response', responseType: "blob" }).pipe(catchError((err, caught) => {
353
+ if (afterGetFile && !handleError)
354
+ afterGetFile();
355
+ return this.registerErrorAndReturnEmptyObservable(err, myGuid, handleError);
356
+ }), finalize(() => { this.tryFinalizeByGuid(myGuid); })).subscribe((response) => {
357
+ let retUrl = window.URL.createObjectURL(response.body);
358
+ let fn = response.headers.get('content-disposition')?.split(';')[1]?.split('filename')[1]?.split('=')[1]?.trim().replace(/\"/g, '');
359
+ getFileCallback(retUrl, filename || fn);
360
+ if (afterGetFile)
361
+ afterGetFile();
362
+ });
363
+ }
364
+ /**
365
+ * Esecuzione di una GET HTTP
366
+ *
367
+ * Casistica particolare in cui viene restituito un file gestito come ObjectURL il cui URL si può gestire dal parametro di callback **getFileCallback**.
368
+ * La chiamata non ha un tipo restituito in quanto il risultato dev'essere gestito attraverso la callback **getFileCallback**
369
+ *
370
+ * @param {string} url URL su cui effettuare la chiamata
371
+ * @param {HttpParams} params Parametri della chiamata
372
+ * @param {string} filename Nome del file che si sta richiedendo, rimane lato Frontend e serve per assegnare arbitrariamente un nome al file restituito, se vuoto viene utilizzata la Content-Disposition della risposta
373
+ * @param {Function} getFileCallback Callback a due parametri (url: string, filename: string) per gestire il risultato del file richiesto. **Utilizzare UtilityService.fileDownload** di @esfaenza/extensions
374
+ * @param {Function} afterGetFile Callback da chiamare dopo aver gestito la risposta del **getFileCallback**, in caso **handleError** fosse **false** verrà richiamato anche in caso di errore
375
+ * @param {boolean} handleError Indica se di default gli errori devono essere gestiti dalla libreria o se devono essere ignorati
376
+ */
377
+ getFile(url, params = null, filename, getFileCallback, afterGetFile = null, handleError = true) {
378
+ let myGuid = this.defaultStartCall(url);
379
+ this.http.get(url, { params: params, headers: this.getHeaders(), observe: 'response', responseType: "blob" }).pipe(catchError((err, caught) => {
380
+ if (afterGetFile && !handleError)
381
+ afterGetFile();
382
+ return this.registerErrorAndReturnEmptyObservable(err, myGuid, handleError);
383
+ }), finalize(() => { this.tryFinalizeByGuid(myGuid); })).subscribe((response) => {
384
+ let retUrl = window.URL.createObjectURL(response.body);
385
+ let fn = response.headers.get('content-disposition')?.split(';')[1]?.split('filename')[1]?.split('=')[1]?.trim().replace(/\"/g, '');
386
+ getFileCallback(retUrl, filename || fn);
387
+ if (afterGetFile)
388
+ afterGetFile();
389
+ });
390
+ }
391
+ /**
392
+ * Download nativo di un file. Internamente utilizza il pattern **window.location.href = "..."**
393
+ *
394
+ * @param {string} url URL su cui effettuare la chiamata
395
+ * @param {HttpParams} params Parametri della chiamata
396
+ */
397
+ getFileNative(url, params = null) {
398
+ let finalUrl = url + (params ? "?" + params.toString() : "");
399
+ window.location.href = finalUrl;
400
+ }
401
+ /**
402
+ * Esecuzione di una GET di un file che emette i vari eventi di progresso di download.
403
+ * Utilizzarla per overridare la dialog nativa di progress del browser e sostituirla con qualcosa tipo quello che fa MEGA.
404
+ *
405
+ * In caso si voglia ottenere il risultato nativo del browser del download utilizzare **getFileNative(url, pars)**
406
+ *
407
+ * @param {string} url URL su cui effettuare la chiamata
408
+ * @param {HttpParams} params Parametri della chiamata
409
+ * @param {Function} getFileCallback Callback a due parametri (url: string, filename: string) per gestire il risultato del file richiesto. **Utilizzare UtilityService.fileDownload** di @esfaenza/extensions
410
+ *
411
+ * @returns {Observable<Download>} Observable dei vari step di progresso del download
412
+ */
413
+ getFileWithProgress(url, params = null, getFileCallback) {
414
+ let myGuid = this.defaultStartCall(url);
415
+ return this.http.get(url, { responseType: 'blob', headers: this.getHeaders(), params: params, observe: 'events', reportProgress: true })
416
+ .pipe(scan((previous, event) => {
417
+ if (this.isHttpProgressEvent(event)) {
418
+ let progress = event.total ? (event.loaded > event.total ? 100 : Math.round((100 * event.loaded) / event.total)) : previous.progress;
419
+ return { progress: progress, state: 'IN_PROGRESS', content: null };
420
+ }
421
+ if (this.isHttpResponse(event)) {
422
+ if (event.body) {
423
+ let cdisp = event.headers.get('content-disposition');
424
+ let cdispFilename = cdisp.split(';')[1].split('filename')[1].split('=')[1].trim().replace(/\"/g, '');
425
+ let retUrl = window.URL.createObjectURL(event.body);
426
+ getFileCallback(retUrl, cdispFilename);
427
+ }
428
+ return { progress: 100, state: 'DONE', content: event.body };
429
+ }
430
+ return previous;
431
+ }, { state: 'PENDING', progress: 0, content: null }), catchError((err, _) => { return this.registerErrorAndReturnEmptyObservable(err, myGuid); }), finalize(() => { this.tryFinalizeByGuid(myGuid); }));
432
+ }
433
+ /**
434
+ * Riconosce se l'evento HTTP è di tipo **HttpResponse** e, se sì, lo casta al tipo corretto per essere utilizzato correttamente nel blocco di codice successivo
435
+ */
436
+ isHttpResponse(event) {
437
+ return event.type === HttpEventType.Response;
438
+ }
439
+ /**
440
+ * Riconosce se l'evento HTTP è di tipo **HttpProgressEvent** e, se sì, lo casta al tipo corretto per essere utilizzato correttamente nel blocco di codice successivo
441
+ */
442
+ isHttpProgressEvent(event) {
443
+ return event.type === HttpEventType.DownloadProgress || event.type === HttpEventType.UploadProgress;
444
+ }
445
+ /**
446
+ * Gestione dell'inizio di una chiamata ad un certo URL, viene generato un GUID da assegnarci, controllata la scadenza della cache,
447
+ * e eventualmente loggato il fatto che sta per essere effettuata una chiamata HTTP
448
+ *
449
+ * @param {string} url Url a cui effettuare la chiamata
450
+ * @returns {string} GUID assegnato alla chiamata
451
+ */
452
+ defaultStartCall(url) {
453
+ let myGuid = this.getGUID();
454
+ this.checkCacheInvalidation(url);
455
+ this.callStatus[myGuid] = true;
456
+ this.log(this.loc("Starting call") + " " + myGuid + " " + this.loc("at URL") + ": " + url);
457
+ return myGuid;
458
+ }
459
+ /**
460
+ * Dato un url vengono controllate le informazioni su tutti gli url da invalidare collegati all'url chiamato e, se presenti in cache, invalidati
461
+ *
462
+ * @param {string} url URL per cui controllare se ci sono chiamate in cache da invalidare
463
+ */
464
+ checkCacheInvalidation(url) {
465
+ let cache = JSON.parse(localStorage.getItem(this.localStorageHttpCacheKey));
466
+ let tmp = /#cache(:?-(\d+))/gi.exec(url);
467
+ let cacheTime = tmp ? tmp[2] : null;
468
+ let normalizedUrl = url.replace("#cache" + (cacheTime ? "-" + cacheTime : ""), "").replace(this.BACKEND_URL, "");
469
+ if (!cache || !this.HTTP_INVALIDATION || !this.HTTP_INVALIDATION[normalizedUrl])
470
+ return;
471
+ let apisToInvalidate = this.HTTP_INVALIDATION[normalizedUrl];
472
+ if (!apisToInvalidate || apisToInvalidate.length == 0)
473
+ return;
474
+ let keysToRemove = [];
475
+ apisToInvalidate.forEach(api => {
476
+ let cacheKey = this.makeCacheKey(api, null);
477
+ for (let item in cache)
478
+ if (item.indexOf(cacheKey) != -1)
479
+ keysToRemove.push(item);
480
+ });
481
+ for (let i = 0; i < keysToRemove.length; i++) {
482
+ let k = keysToRemove[i];
483
+ this.log(this.loc("Invlalidating cache element") + " " + k);
484
+ delete cache[k];
485
+ }
486
+ localStorage.setItem(this.localStorageHttpCacheKey, JSON.stringify(cache));
487
+ }
488
+ /**
489
+ * Finalizzazione di una chiamata
490
+ *
491
+ * @param {string} guid GUID collegato alla chiamata appena terminata
492
+ */
493
+ tryFinalizeByGuid(guid) {
494
+ this.log(this.loc("Finalizing call") + " " + guid + " " + this.loc("with status") + ": " + (this.callStatus[guid] ? this.loc('Success') : this.loc('Failure')));
495
+ //Alla prima chiamata buona, significa che almeno il login ce l'ho. Posso mettermi in modalità redirectInProgress false
496
+ //e riiniziare a valutare errori di javashit
497
+ if (this.callStatus[guid] && this.ExtensionsImpl.readRedirectionStatus())
498
+ this.ExtensionsImpl.writeRedirectionStatus(false);
499
+ //In ogni caso questa posso rimuoverla
500
+ delete this.callStatus[guid];
501
+ }
502
+ /**
503
+ * Helper che dato un unico File o una lista di File crea un oggetto FormData che può essere inviato comodamente
504
+ * ad un backend ASP.NET da cui si potrà accedere a Request.Form.Files
505
+ *
506
+ * @param {File | File[]} fileArrayOrFile Singolo File o lista di File. N.B: nella firma della funzione viene considerato **any** per fare test sulle proprietà
507
+ * invece che fare test con l'**istanceof**
508
+ *
509
+ * @returns {FormData} FormData contenente tutti i file passati
510
+ */
511
+ getFilesFormData(fileArrayOrFile) {
512
+ var formData = new FormData();
513
+ if (fileArrayOrFile) {
514
+ if (fileArrayOrFile.length)
515
+ fileArrayOrFile.forEach(t => { formData.append("file", t, t.name); });
516
+ else if (fileArrayOrFile.name)
517
+ formData.append("files", fileArrayOrFile, fileArrayOrFile.name);
518
+ }
519
+ return formData;
520
+ }
521
+ /**
522
+ * Helper che in base ai parametri disponibili genera gli Header HTTP per la chiamata da effettuare
523
+ *
524
+ * @param {string} contentType Indica se aggiungere agli header "Content-Type", valorizzato al valore del parametro
525
+ * @param {string} accept Indica se aggiungere agli header "Accept", valorizzato al valore del parametro
526
+ * @param {boolean} includeAuth Indica se aggiungere agli header "Authorization", valorizzato col token recuperato dall'hook **retrieveAccessToken** della classe di estensione
527
+ * @param {string} transactionId Indica se aggiungere agli header "X-TX-ID", valorizzato al valore del parametro
528
+ *
529
+ * @returns {HttpHeaders} Header generati in base ai parametri
530
+ */
531
+ getHeaders(transactionId = "", includeAuth = true, contentType = "application/json", accept = "application/json") {
532
+ var headers = new HttpHeaders();
533
+ var authtoken = this.ExtensionsImpl.retrieveAccessToken();
534
+ if (contentType)
535
+ headers = headers.append("Content-Type", contentType);
536
+ if (transactionId)
537
+ headers = headers.append("X-TX-ID", transactionId);
538
+ if (authtoken && includeAuth)
539
+ headers = headers.append("Authorization", "Bearer " + authtoken);
540
+ if (accept)
541
+ headers = headers.append("Accept", "application/json");
542
+ headers = headers.append("Accept-Language", this.LOCALE ?? 'it-IT');
543
+ return headers;
544
+ }
545
+ /**
546
+ * Gestione di default degli errori
547
+ *
548
+ * @param {any} res Risultato della chiamata effettuata
549
+ * @param {string} guid Identificativo GUID della chiamata effettuata
550
+ */
551
+ async onError(res, guid) {
552
+ this.callStatus[guid] = false;
553
+ //Mi assicuro che tutti gli errori durante il redirect al login vengano ignorati
554
+ if (this.ExtensionsImpl.readRedirectingToLogin()) {
555
+ this.log(this.loc("Redirecting to Login, ignoring HTTP error on call") + " " + guid);
556
+ return;
557
+ }
558
+ //Mi assicuro che venga gestito un solo errore per volta
559
+ if (this.ExtensionsImpl.readHandlingErrorStatus()) {
560
+ this.log(this.loc("Already Handling an error, ignoring HTTP error on call") + " " + guid);
561
+ return;
562
+ }
563
+ else
564
+ this.ExtensionsImpl.writeHandlingErrorStatus(true);
565
+ let finalError = "";
566
+ let finalStatus = "";
567
+ if (this.isTypeError(res)) {
568
+ finalError = res.message;
569
+ finalStatus = "HTTP Service Internal Error";
570
+ }
571
+ else if (this.isHttpErrorResponse(res)) {
572
+ finalError = await this.getHttpErrorText(res.error);
573
+ finalStatus = res.status.toString();
574
+ switch (res.status) {
575
+ // Unauthorized
576
+ case 401:
577
+ if (this.ExtensionsImpl.readRedirectionStatus()) {
578
+ this.log(this.loc("Error 401 on call") + " " + guid + " " + this.loc("with redirect already in progress. Ignoring this event"));
579
+ return;
580
+ }
581
+ this.log(this.loc("Error 401 on call") + " " + guid + " " + this.loc("redirecting to login."));
582
+ this.ExtensionsImpl.writeRedirectionStatus(true);
583
+ this.ExtensionsImpl.writeRedirectingToLogin(true);
584
+ this.ExtensionsImpl.redirectToLogin();
585
+ return;
586
+ // Handled exception
587
+ case 400:
588
+ // No Permissions
589
+ case 403:
590
+ this.ExtensionsImpl.handleBlockingException(res.status, finalError);
591
+ return;
592
+ // Not found
593
+ case 404:
594
+ this.ExtensionsImpl.handleBlockingException(res.status, this.loc("Resource not found"));
595
+ return;
596
+ // NotConfiguredException
597
+ case 444:
598
+ if (this.ExtensionsImpl.readRedirectionStatus())
599
+ this.log(this.loc("Error 444 on call") + " " + guid + " " + this.loc("with redirect already in progress. Ignoring this event"));
600
+ else if (!this.ExtensionsImpl.handleNotConfiguredException())
601
+ this.ExtensionsImpl.handleBlockingException(res.status, finalError);
602
+ return;
603
+ case 0:
604
+ finalError = "Server might be offline" + (res.statusText ? " (" + res.statusText + ") " : "");
605
+ }
606
+ }
607
+ this.ExtensionsImpl.handleException(finalStatus, finalError);
608
+ }
609
+ /**
610
+ * Dato un errore restituisce una promise con la stringa finale dell'errore in modo da poter fare un await
611
+ *
612
+ * @param {any} err Errore da controllare
613
+ *
614
+ * @returns {Promise<string>} Promise che risolve con la stringa finale dell'errore
615
+ */
616
+ getHttpErrorText(err) {
617
+ // Se ho un Blob può essere o un CallResult o suppongo una semplice stringa,
618
+ // altrimenti potrebbe essere direttamente un CallResult, oppure una semplice stringa
619
+ return new Promise((resolve) => {
620
+ if (err instanceof Blob) {
621
+ let reader = new FileReader();
622
+ reader.onload = (e) => {
623
+ let errMsg = e.target.result;
624
+ let jsonerrMsg;
625
+ try {
626
+ jsonerrMsg = JSON.parse(errMsg);
627
+ }
628
+ catch (e) { }
629
+ return resolve(jsonerrMsg && this.isCallResult(jsonerrMsg) ? jsonerrMsg.error.message : errMsg);
630
+ };
631
+ reader.readAsText(err);
632
+ }
633
+ else if (this.isCallResult(err))
634
+ return resolve(err.error.message);
635
+ else
636
+ return resolve(err?.toString());
637
+ });
638
+ }
639
+ /**
640
+ * Riconosce se l'oggetto è di tipo **CallResult** e, se sì, lo casta al tipo corretto per essere utilizzato correttamente nel blocco di codice successivo
641
+ *
642
+ * @param {any} err Errore da controllare
643
+ */
644
+ isCallResult(err) {
645
+ return !!err?.error?.message;
646
+ }
647
+ /**
648
+ * Riconosce se l'errore è di tipo **HttpErrorResponse** e, se sì, lo casta al tipo corretto per essere utilizzato correttamente nel blocco di codice successivo
649
+ *
650
+ * @param {any} err Errore da controllare
651
+ */
652
+ isHttpErrorResponse(err) {
653
+ return err instanceof HttpErrorResponse;
654
+ }
655
+ /**
656
+ * Riconosce se l'errore è di tipo **TypeError** e, se sì, lo casta al tipo corretto per essere utilizzato correttamente nel blocco di codice successivo
657
+ *
658
+ * @param {any} err Errore da controllare
659
+ */
660
+ isTypeError(err) {
661
+ return err.name == "TypeError";
662
+ }
663
+ /**
664
+ * Come dice il nome, registra un errore e restituisce un Observable vuoto come risultato della chiamata
665
+ *
666
+ * @param {any} res Risultato della chiamata effettuata
667
+ * @param {string} guid Identificativo GUID della chiamata effettuata
668
+ * @param {boolean} handleError Indica se gestire l'errore via libreria o se limitarsi a restituire l'Observable vuoto
669
+ *
670
+ * @returns {Observable<any>} Observable vuoto
671
+ */
672
+ registerErrorAndReturnEmptyObservable(res, guid, handleError = true) {
673
+ if (handleError)
674
+ this.onError(res, guid);
675
+ return new Observable(() => { });
676
+ }
677
+ /**
678
+ * Dato un Url e dei parametri cerca di recuperare l'eventuale oggetto già salvato in cache con le informazioni base della cache stessa
679
+ *
680
+ * @param {string} url URL su cui effettuare la chiamata
681
+ * @param {HttpParams} params Parametri della chiamata (nulli in caso di POST)
682
+ *
683
+ * @returns {{ finalUrl: string, cache: boolean, cacheKey: string, cacheTime: string, cacheItem: any }} Oggetto contenente le informazioni sulla cache per l'oggetto specificato
684
+ */
685
+ tryGetCacheInformations(url, params) {
686
+ let cachingKey = null, cacheTime = null, cache = null, item = null;
687
+ let useCaching = !!(/#cache/gi.exec(url));
688
+ if (useCaching) {
689
+ let tmp = /#cache(:?-(\d+))/gi.exec(url);
690
+ cacheTime = tmp ? tmp[2] : null;
691
+ url = url.replace("#cache" + (cacheTime ? "-" + cacheTime : ""), "");
692
+ if (this.untimedCacheExpired() && !cacheTime)
693
+ this.resetHttpUntimedCacheStorage();
694
+ cachingKey = this.makeCacheKey(url, params);
695
+ let cacheKey = cacheTime ? this.localStorageHttpTimedCacheKey : this.localStorageHttpCacheKey;
696
+ let cacheLs = localStorage.getItem(cacheKey);
697
+ let cache = cacheLs ? JSON.parse(cacheLs) : {};
698
+ if (cache && cache[cachingKey] && !this.timedCacheItemExpired(cache[cachingKey])) {
699
+ // Se gestisco il tempo esatto della cache prima di restituire l'oggetto cachato lo ripulisco
700
+ // dalle proprietà interne che gli ho aggiunto per controllarne la scadenza
701
+ if (cacheTime)
702
+ delete cache[cachingKey].__expire;
703
+ item = cache[cachingKey];
704
+ }
705
+ }
706
+ return { finalUrl: url, cache: useCaching, cacheKey: cachingKey, cacheTime: cacheTime, cacheItem: item };
707
+ }
708
+ /**
709
+ * Inserisce un oggetto nella cache appropriata in base alle informazioni contenute nel parametro **cacheInfos**
710
+ *
711
+ * @param {T} item Oggetto da inserire nella cache
712
+ * @param {{ finalUrl: string, cache: boolean, cacheKey: string, cacheTime: string, cacheItem: any }} cacheInfos Informazioni sulla cache recuperate da una chiamata precedente a **tryGetCacheInformations**
713
+ */
714
+ cacheResponse(item, cacheInfos) {
715
+ let cacheKey = cacheInfos.cacheTime ? this.localStorageHttpTimedCacheKey : this.localStorageHttpCacheKey;
716
+ let cacheLs = localStorage.getItem(cacheKey);
717
+ let cache = cacheLs ? JSON.parse(cacheLs) : {};
718
+ cache[cacheInfos.cacheKey] = item;
719
+ if (cacheInfos.cacheTime)
720
+ cache[cacheInfos.cacheKey].__expire = dayjs().add(cacheInfos.cacheTime, "seconds");
721
+ localStorage.setItem(cacheKey, JSON.stringify(cache));
722
+ }
723
+ /**
724
+ * Controlla se la cache per le chiamate senza expire time è scaduta
725
+ *
726
+ * @returns {boolean} **true** se la cache è scaduta e dev'essere ripulita, **false** altrimenti
727
+ */
728
+ untimedCacheExpired() {
729
+ let expire = JSON.parse(localStorage.getItem(this.localStorageHttpCacheExpireKey));
730
+ return !expire || expire && dayjs(expire) < dayjs();
731
+ }
732
+ /**
733
+ * Controlla se la cache per una chiamata che ha un tempo di vita ben definito è scaduta o meno
734
+ *
735
+ * @param {any} item Oggetto recuperato dalla cache a cui ho aggiunto la chiave interna __expire
736
+ *
737
+ * @returns {boolean} **true** se la cache è scaduta e dev'essere ripulita, **false** altrimenti
738
+ */
739
+ timedCacheItemExpired(item) {
740
+ return dayjs(item.__expire) < dayjs();
741
+ }
742
+ /**
743
+ * Ripulisce la cache e imposta la prossima scadenza ad adesso + **CLIENT_CACHE_DURATION_S** (token valorizzato in fase di configurazione dalla proprietà **clientCacheDurationS** della classe **HttpServiceModuleConfig**)
744
+ */
745
+ resetHttpUntimedCacheStorage() {
746
+ localStorage.setItem(this.localStorageHttpCacheKey, JSON.stringify({}));
747
+ localStorage.setItem(this.localStorageHttpCacheExpireKey, JSON.stringify(dayjs().add(this.CLIENT_CACHE_DURATION_S ?? 3600, "second")));
748
+ }
749
+ /**
750
+ * Ripulisce la cache delle chiamate con un tempo di expire definito
751
+ */
752
+ resetHttpTimedCacheStorage() {
753
+ localStorage.setItem(this.localStorageHttpTimedCacheKey, JSON.stringify({}));
754
+ }
755
+ /**
756
+ * Genera una chiave per la cache delle chiamate in base ad URL e Parametri HTTP
757
+ *
758
+ * @param {string} url URL su cui effettuare la chiamata
759
+ * @param {HttpParams} params Parametri della chiamata
760
+ *
761
+ * @returns {string} Chiave che rappresenta in maniera univoca la chiamata
762
+ */
763
+ makeCacheKey(url, params) {
764
+ let authKeyPart = (this.me ? this.me.Idtenant : "") + (this.me && this.CACHE_BY_USER ? this.me.IdUser : "");
765
+ let paramsKeyPart = params && params.keys().length > 0 ? params.keys().reduce((prev, next) => prev + next + '=' + params.get(next), "") : "";
766
+ return authKeyPart + url + paramsKeyPart;
767
+ }
768
+ /**
769
+ * Generazione GUID
770
+ *
771
+ * @returns {string} Nuovo GUID generato in maniera casuale
772
+ */
773
+ getGUID() {
774
+ return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
775
+ var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8);
776
+ return v.toString(16);
777
+ });
778
+ }
779
+ /**
780
+ * Metodo per scrivere log a console qualora **DEBUG_MODE** risultasse **true**
781
+ *
782
+ * @param {string} message Messaggio di log
783
+ */
784
+ log(message) {
785
+ if (this.DEBUG_MODE)
786
+ console.log("@httpservice: " + message);
787
+ }
788
+ /**
789
+ * Helper per la localizzazione dei messaggi
790
+ *
791
+ * @param {string} message Messaggio da localizzare
792
+ *
793
+ * @returns {string} Messaggio localizzato
794
+ */
795
+ loc(message) {
796
+ if (!Loc[message]) {
797
+ console.warn("Untranslated message: " + message);
798
+ return "";
799
+ }
800
+ return Loc[message][this.LOCALE];
801
+ }
802
+ }
803
+ HTTPService.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "13.1.1", ngImport: i0, type: HTTPService, deps: [{ token: BACKEND_URL }, { token: HttpServiceExtensions }, { token: HTTP_INVALIDATION, optional: true }, { token: HTTP_LOCALE, optional: true }, { token: APP_NAME, optional: true }, { token: CLIENT_CACHE_DURATION_S, optional: true }, { token: CACHE_BY_USER, optional: true }, { token: DEBUG_MODE, optional: true }, { token: i2.HttpClient }], target: i0.ɵɵFactoryTarget.Injectable });
804
+ HTTPService.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "13.1.1", ngImport: i0, type: HTTPService });
805
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "13.1.1", ngImport: i0, type: HTTPService, decorators: [{
806
+ type: Injectable
807
+ }], ctorParameters: function () { return [{ type: undefined, decorators: [{
808
+ type: Inject,
809
+ args: [BACKEND_URL]
810
+ }] }, { type: HttpServiceExtensions }, { type: undefined, decorators: [{
811
+ type: Optional
812
+ }, {
813
+ type: Inject,
814
+ args: [HTTP_INVALIDATION]
815
+ }] }, { type: undefined, decorators: [{
816
+ type: Optional
817
+ }, {
818
+ type: Inject,
819
+ args: [HTTP_LOCALE]
820
+ }] }, { type: undefined, decorators: [{
821
+ type: Optional
822
+ }, {
823
+ type: Inject,
824
+ args: [APP_NAME]
825
+ }] }, { type: undefined, decorators: [{
826
+ type: Optional
827
+ }, {
828
+ type: Inject,
829
+ args: [CLIENT_CACHE_DURATION_S]
830
+ }] }, { type: undefined, decorators: [{
831
+ type: Optional
832
+ }, {
833
+ type: Inject,
834
+ args: [CACHE_BY_USER]
835
+ }] }, { type: undefined, decorators: [{
836
+ type: Optional
837
+ }, {
838
+ type: Inject,
839
+ args: [DEBUG_MODE]
840
+ }] }, { type: i2.HttpClient }]; } });
841
+
842
+ class HttpserviceModule {
843
+ static forRoot(config) {
844
+ return {
845
+ ngModule: HttpserviceModule,
846
+ providers: [
847
+ HTTPService,
848
+ HttpServiceExtensions,
849
+ { provide: HTTP_INVALIDATION, useValue: config?.httpInvalidation },
850
+ { provide: CLIENT_CACHE_DURATION_S, useValue: config?.clientCacheDurationS },
851
+ { provide: BACKEND_URL, useValue: config?.backendUrl },
852
+ { provide: HTTP_LOCALE, useValue: config?.httpLocale || 'it-IT' },
853
+ { provide: APP_NAME, useValue: config?.appName },
854
+ { provide: CACHE_BY_USER, useValue: config?.cacheByUser },
855
+ { provide: DEBUG_MODE, useValue: config?.debugMode }
856
+ ]
857
+ };
858
+ }
859
+ }
860
+ HttpserviceModule.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "13.1.1", ngImport: i0, type: HttpserviceModule, deps: [], target: i0.ɵɵFactoryTarget.NgModule });
861
+ HttpserviceModule.ɵmod = i0.ɵɵngDeclareNgModule({ minVersion: "12.0.0", version: "13.1.1", ngImport: i0, type: HttpserviceModule });
862
+ HttpserviceModule.ɵinj = i0.ɵɵngDeclareInjector({ minVersion: "12.0.0", version: "13.1.1", ngImport: i0, type: HttpserviceModule });
863
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "13.1.1", ngImport: i0, type: HttpserviceModule, decorators: [{
864
+ type: NgModule
865
+ }] });
866
+
867
+ /**
868
+ * Classe di configurazione per il Modulo della libreria
869
+ */
870
+ class HttpServiceModuleConfig {
871
+ }
872
+
873
+ class Download {
874
+ }
875
+
876
+ /*
877
+ * Public API Surface of httpservice
878
+ */
879
+
880
+ /**
881
+ * Generated bundle index. Do not edit.
882
+ */
883
+
884
+ export { Download, HTTPService, HttpServiceExtensions, HttpServiceModuleConfig, HttpserviceModule };
885
+ //# sourceMappingURL=esfaenza-httpservice.mjs.map