forked from Nodonisko/ionic-cache
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcache.service.ts
493 lines (428 loc) · 12.4 KB
/
cache.service.ts
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
import { Injectable } from '@angular/core';
import { Observable, Subject } from 'rxjs';
import { defer, from, fromEvent, merge, throwError } from 'rxjs';
import { share, map, catchError } from 'rxjs/operators';
import { CacheStorageService, StorageCacheItem } from './cache-storage';
export interface CacheConfig {
keyPrefix?: string;
}
export const MESSAGES = {
0: 'Cache initialization error: ',
1: 'Cache is not enabled.',
2: 'Cache entry already expired: ',
3: 'No such key: ',
4: 'No entries were deleted, because browser is offline.'
};
export type CacheValueFactory<T> = () => Promise<T>;
// @dynamic
@Injectable()
export class CacheService {
private ttl: number = 60 * 60; // one hour
private cacheEnabled: boolean = true;
private invalidateOffline: boolean = false;
private networkStatusChanges: Observable<boolean>;
private networkStatus: boolean = true;
static request: any;
static response: any;
static responseOptions: any;
static httpDeprecated: boolean = false;
constructor(
private _storage: CacheStorageService
) {
this.loadHttp();
this.watchNetworkInit();
this.loadCache();
}
private async loadCache() {
try {
await this._storage.ready();
this.cacheEnabled = true;
} catch (e) {
this.cacheEnabled = false;
console.error(MESSAGES[0], e);
}
}
private async loadHttp() {
if (CacheService.request && CacheService.response) {
return;
}
let http;
// try load @angular/http deprecated or @angular/common/http
try {
http = await import('@angular/http');
CacheService.httpDeprecated = true;
} catch (e) {
http = await import('@angular/common/http');
}
CacheService.request = http.Request || http.HttpRequest;
CacheService.response = http.Response || http.HttpResponse;
CacheService.responseOptions = http.ResponseOptions;
}
async ready(): Promise<any> {
await this._storage.ready();
}
/**
* @description Disable or enable cache
*/
enableCache(enable: boolean = true) {
this.cacheEnabled = enable;
}
/**
* @description Delete DB table and create new one
* @return {Promise<any>}
*/
private async resetDatabase(): Promise<any> {
await this.ready();
let items = await this._storage.all();
return Promise.all(
items
.map(item => this.removeItem(item.key))
);
}
/**
* @description Set default TTL
* @param {number} ttl - TTL in seconds
*/
setDefaultTTL(ttl: number): number {
return (this.ttl = ttl);
}
/**
* @description Set if expired cache should be invalidated if device is offline
* @param {boolean} offlineInvalidate
*/
setOfflineInvalidate(offlineInvalidate: boolean) {
this.invalidateOffline = !offlineInvalidate;
}
/**
* @description Start watching if devices is online or offline
*/
private watchNetworkInit() {
this.networkStatus = navigator.onLine;
const connect = fromEvent(window, 'online').pipe(map(() => true)),
disconnect = fromEvent(window, 'offline').pipe(map(() => false));
this.networkStatusChanges = merge(connect, disconnect).pipe(share());
this.networkStatusChanges.subscribe(status => {
this.networkStatus = status;
});
}
/**
* @description Stream of network status changes
* * @return {Observable<boolean>} network status stream
*/
getNetworkStatusChanges() {
return this.networkStatusChanges;
}
/**
* @description Check if devices is online
* @return {boolean} network status
*/
isOnline() {
return this.networkStatus;
}
/**
* @description Save item to cache
* @param {string} key - Unique key
* @param {any} data - Data to store
* @param {string} [groupKey] - group key
* @param {number} [ttl] - TTL in seconds
* @return {Promise<any>} - saved data
*/
saveItem(
key: string,
data: any,
groupKey: string = 'none',
ttl: number = this.ttl
): Promise<any> {
if (!this.cacheEnabled) {
throw new Error(MESSAGES[1]);
}
const expires = new Date().getTime() + ttl * 1000,
type = CacheService.isRequest(data) ? 'request' : typeof data,
value = JSON.stringify(data);
return this._storage.set(key, {
value,
expires,
type,
groupKey
});
}
/**
* @description Delete item from cache
* @param {string} key - Unique key
* @return {Promise<any>} - query execution promise
*/
removeItem(key: string): Promise<any> {
if (!this.cacheEnabled) {
throw new Error(MESSAGES[1]);
}
return this._storage.remove(key);
}
/**
* @description Removes all items with a key that matches pattern
* @return {Promise<any>}
*/
async removeItems(pattern: string): Promise<any> {
if (!this.cacheEnabled) {
throw new Error(MESSAGES[1]);
}
let regex = new RegExp(`^${pattern.split('*').join('.*')}$`);
let items = await this._storage.all();
return Promise.all(
items
.map(item => item.key)
.filter(key => key && regex.test(key))
.map(key => this.removeItem(key))
);
}
/**
* @description Get item from cache without expire check etc.
* @param {string} key - Unique key
* @return {Promise<any>} - data from cache
*/
async getRawItem<T = any>(key: string): Promise<StorageCacheItem> {
if (!this.cacheEnabled) {
throw new Error(MESSAGES[1]);
}
try {
let data = await this._storage.get(key);
if (!!data) {
return data;
}
throw new Error('');
} catch (err) {
throw new Error(MESSAGES[3] + key);
}
}
async getRawItems() {
return this._storage.all();
}
/**
* @description Check if item exists in cache regardless if expired or not
* @param {string} key - Unique key
* @return {Promise<boolean | string>} - boolean - true if exists
*/
async itemExists(key: string): Promise<boolean | string> {
if (!this.cacheEnabled) {
throw new Error(MESSAGES[1]);
}
return this._storage.exists(key);
}
/**
* @description Get item from cache with expire check and correct type assign
* @param {string} key - Unique key
* @return {Promise<any>} - data from cache
*/
async getItem<T = any>(key: string): Promise<T> {
if (!this.cacheEnabled) {
throw new Error(MESSAGES[1]);
}
let data = await this.getRawItem(key);
if (data.expires < new Date().getTime() && (this.invalidateOffline || this.isOnline())) {
throw new Error(MESSAGES[2] + key);
}
return CacheService.decodeRawData(data);
}
async getOrSetItem<T>(
key: string,
factory: CacheValueFactory<T>,
groupKey?: string,
ttl?: number
): Promise<T> {
let val: T;
try {
val = await this.getItem<T>(key);
} catch (error) {
val = await factory();
await this.saveItem(key, val, groupKey, ttl);
}
return val;
}
/**
* @description Decode raw data from DB
* @param {any} data - Data
* @return {any} - decoded data
*/
static decodeRawData(data: StorageCacheItem): any {
let dataJson = JSON.parse(data.value);
if (CacheService.isRequest(dataJson)) {
let response: any = {
body: dataJson._body || dataJson.body,
status: dataJson.status,
headers: dataJson.headers,
statusText: dataJson.statusText,
url: dataJson.url
};
if (CacheService.responseOptions) {
response.type = dataJson.type;
response = new CacheService.responseOptions(response);
}
return new CacheService.response(response);
}
return dataJson;
}
/**
* @description Load item from cache if it's in cache or load from origin observable
* @param {string} key - Unique key
* @param {any} observable - Observable with data
* @param {string} [groupKey] - group key
* @param {number} [ttl] - TTL in seconds
* @return {Observable<any>} - data from cache or origin observable
*/
loadFromObservable<T = any>(
key: string,
observable: any,
groupKey?: string,
ttl?: number
): Observable<T> {
if (!this.cacheEnabled) return observable;
observable = observable.pipe(share());
return defer(() => {
return from(this.getItem(key)).pipe(
catchError(e => {
observable.subscribe(
res => {
return this.saveItem(key, res, groupKey, ttl);
},
error => {
return throwError(error);
}
);
return observable;
})
);
});
}
/**
* @description Load item from cache if it's in cache or load from origin observable
* @param {string} key - Unique key
* @param {any} observable - Observable with data
* @param {string} [groupKey] - group key
* @param {number} [ttl] - TTL in seconds
* @param {string} [delayType='expired']
* @param {string} [metaKey] - property on T to which to assign meta data
* @return {Observable<any>} - data from cache or origin observable
*/
loadFromDelayedObservable<T = any>(
key: string,
observable: Observable<T>,
groupKey?: string,
ttl: number = this.ttl,
delayType: string = 'expired',
metaKey?: string
): Observable<T> {
if (!this.cacheEnabled) return observable;
const observableSubject = new Subject<T>();
observable = observable.pipe(share());
const subscribeOrigin = () => {
observable.subscribe(
res => {
this.saveItem(key, res, groupKey, ttl);
observableSubject.next(res);
observableSubject.complete();
},
err => {
observableSubject.error(err);
},
() => {
observableSubject.complete();
}
);
};
this.getItem<T>(key)
.then(data => {
if (metaKey) {
data[metaKey] = data[metaKey] || {};
data[metaKey].fromCache = true;
}
observableSubject.next(data);
if (delayType === 'all') {
subscribeOrigin();
} else {
observableSubject.complete();
}
})
.catch(e => {
this.getRawItem<T>(key)
.then(res => {
let result = CacheService.decodeRawData(res);
if (metaKey) {
result[metaKey] = result[metaKey] || {};
result[metaKey].fromCache = true;
}
observableSubject.next(result);
subscribeOrigin();
})
.catch(() => subscribeOrigin());
});
return observableSubject.asObservable();
}
/**
* Perform complete cache clear
* @return {Promise<any>}
*/
clearAll(): Promise<any> {
if (!this.cacheEnabled) {
throw new Error(MESSAGES[2]);
}
return this.resetDatabase();
}
/**
* @description Remove all expired items from cache
* @param {boolean} ignoreOnlineStatus -
* @return {Promise<any>} - query promise
*/
async clearExpired(ignoreOnlineStatus = false): Promise<any> {
if (!this.cacheEnabled) {
throw new Error(MESSAGES[2]);
}
if (!this.isOnline() && !ignoreOnlineStatus) {
throw new Error(MESSAGES[4]);
}
let items = await this._storage.all();
let datetime = new Date().getTime();
return Promise.all(
items
.filter(item => item.expires < datetime)
.map(item => this.removeItem(item.key))
);
}
/**
* @description Remove all item with specified group
* @param {string} groupKey - group key
* @return {Promise<any>} - query promise
*/
async clearGroup(groupKey: string): Promise<any> {
if (!this.cacheEnabled) {
throw new Error(MESSAGES[2]);
}
let items = await this._storage.all();
return Promise.all(
items
.filter(item => item.groupKey === groupKey)
.map(item => this.removeItem(item.key))
);
}
/**
* @description Check if it's an request
* @param {any} data - Variable to test
* @return {boolean} - data from cache
*/
static isRequest(data: any): boolean {
let orCondition =
data &&
typeof data === 'object' &&
data.hasOwnProperty('status') &&
data.hasOwnProperty('statusText') &&
data.hasOwnProperty('headers') &&
data.hasOwnProperty('url');
if (CacheService.httpDeprecated) {
orCondition =
orCondition &&
data.hasOwnProperty('type') &&
data.hasOwnProperty('_body');
} else {
orCondition = orCondition && data.hasOwnProperty('body');
}
return data && ((CacheService.request && data instanceof CacheService.request) || orCondition);
}
}