forked from angelnikolov/ts-cacheable
-
Notifications
You must be signed in to change notification settings - Fork 0
/
cacheable.decorator.spec.ts
710 lines (626 loc) · 21.4 KB
/
cacheable.decorator.spec.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
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
import { combineLatest, forkJoin, Observable, Subject, timer } from 'rxjs';
import { mapTo, startWith } from 'rxjs/operators';
import { CacheBuster } from './cache-buster.decorator';
import { Cacheable } from './cacheable.decorator';
const cacheBusterNotifier = new Subject();
class Service {
mockServiceCall(parameter) {
return timer(1000).pipe(mapTo({ payload: parameter }));
}
mockSaveServiceCall() {
return timer(1000).pipe(mapTo('SAVED'));
}
@Cacheable()
getData(parameter: string) {
return this.mockServiceCall(parameter);
}
@Cacheable()
getDataWithParamsObj(parameter: any) {
return this.mockServiceCall(parameter);
}
@Cacheable()
getDataAndReturnCachedStream(parameter: string) {
return this.mockServiceCall(parameter);
}
@Cacheable({
async: true
})
getDataAsync(parameter: string) {
return this.mockServiceCall(parameter);
}
@Cacheable({
maxAge: 7500
})
getDataWithExpiration(parameter: string) {
return this.mockServiceCall(parameter);
}
@Cacheable({
maxAge: 7500,
slidingExpiration: true
})
getDataWithSlidingExpiration(parameter: string) {
return this.mockServiceCall(parameter);
}
@Cacheable({
maxCacheCount: 5
})
getDataWithMaxCacheCount(parameter: string) {
return this.mockServiceCall(parameter);
}
@Cacheable({
maxAge: 7500,
maxCacheCount: 5
})
getDataWithMaxCacheCountAndExpiration(parameter: string) {
return this.mockServiceCall(parameter);
}
@Cacheable({
maxAge: 7500,
maxCacheCount: 5,
slidingExpiration: true
})
getDataWithMaxCacheCountAndSlidingExpiration(parameter: string) {
return this.mockServiceCall(parameter);
}
@Cacheable({
cacheResolver: (_oldParameters, newParameters) => {
return newParameters.find(param => !!param.straightToLastCache);
}
})
getDataWithCustomCacheResolver(
parameter: string,
_cacheRerouterParameter?: { straightToLastCache: boolean }
) {
return this.mockServiceCall(parameter);
}
@Cacheable({
shouldCacheDecider: (response: { payload: string }) => {
return response.payload === 'test';
}
})
getDataWithCustomCacheDecider(parameter: string) {
return this.mockServiceCall(parameter);
}
@CacheBuster({
cacheBusterNotifier: cacheBusterNotifier
})
saveDataAndCacheBust() {
return this.mockSaveServiceCall();
}
@Cacheable({
cacheBusterObserver: cacheBusterNotifier.asObservable()
})
getDataWithCacheBusting(parameter: string) {
return this.mockServiceCall(parameter);
}
}
describe('CacheableDecorator', () => {
let service: Service = null;
let mockServiceCallSpy: jasmine.Spy = null;
beforeEach(() => {
jasmine.clock().install();
service = new Service();
mockServiceCallSpy = spyOn(service, 'mockServiceCall').and.callThrough();
});
afterEach(() => {
jasmine.clock().uninstall();
});
/**
* do not use async await when using jasmine.clock()
* we can mitigate this but will make our tests slower
* https://www.google.bg/search?q=jasmine.clock.install+%2B+async+await&oq=jasmine.clock.install+%2B+async+await&aqs=chrome..69i57.4240j0j7&sourceid=chrome&ie=UTF-8
*/
it('return cached data up until a new parameter is passed and the cache is busted', () => {
const asyncFreshData = _timedStreamAsyncAwait(
service.getData('test'),
1000
);
expect(asyncFreshData).toEqual({ payload: 'test' });
expect(mockServiceCallSpy).toHaveBeenCalledTimes(1);
const cachedResponse = _timedStreamAsyncAwait(service.getData('test'));
expect(cachedResponse).toEqual({ payload: 'test' });
/**
* response acquired from cache, so no incrementation on the service spy call counter is expected here
*/
expect(mockServiceCallSpy).toHaveBeenCalledTimes(1);
const cachedResponse2 = _timedStreamAsyncAwait(service.getData('test2'));
expect(cachedResponse2).toEqual(null);
/**
* no cache for 'test2', but service call was made so the spy counter is incremented
*/
expect(mockServiceCallSpy).toHaveBeenCalledTimes(2);
const cachedResponse3 = _timedStreamAsyncAwait(
service.getData('test3'),
1000
);
/**
* service call is made and waited out
*/
expect(cachedResponse3).toEqual({ payload: 'test3' });
/**
* this should NOT return cached response, since the currently cached one should be 'test3'
*/
const cachedResponse4 = _timedStreamAsyncAwait(service.getData('test'));
expect(cachedResponse4).toEqual(null);
expect(mockServiceCallSpy).toHaveBeenCalledTimes(4);
});
it('returns observables in cache with a referential type params', () => {
let params = {
number: [1]
};
/**
* call the service endpoint with current params values
*/
service.getDataWithParamsObj(params);
/**
* return the response
*/
jasmine.clock().tick(1000);
/**
* change params object values
*/
params.number.push(2);
/**
* call again..
*/
service.getDataWithParamsObj(params);
/**
* service call count should still be 2, since param object has changed
*/
expect(mockServiceCallSpy).toHaveBeenCalledTimes(2);
});
it('return the cached observable up until it completes or errors', () => {
/**
* call the service endpoint five hundred times with the same parameter
* but the service should only be called once, since the observable will be cached
*/
for (let i = 0; i < 500; i++) {
service.getDataAndReturnCachedStream('test');
}
expect(mockServiceCallSpy).toHaveBeenCalledTimes(1);
/**
* return the response
*/
jasmine.clock().tick(1000);
/**
* call again..
*/
service.getDataAndReturnCachedStream('test');
/**
* service call count should still be 1, since we are returning from cache now
*/
expect(mockServiceCallSpy).toHaveBeenCalledTimes(1);
});
it('with async:true return cached data ASYNCHRONOUSLY up until a new parameter is passed and the cache is busted', () => {
const asyncFreshData = _timedStreamAsyncAwait(
service.getDataAsync('test'),
1000
);
expect(asyncFreshData).toEqual({ payload: 'test' });
expect(mockServiceCallSpy).toHaveBeenCalledTimes(1);
const cachedResponseTry1 = _timedStreamAsyncAwait(
service.getDataAsync('test')
);
/**
* async cache hasn't resolved yet
* we need to wait a tick out first
*/
expect(cachedResponseTry1).toEqual(null);
/**
* 1 millisecond delay added, so the async cache resolves
*/
const cachedResponseTry2 = _timedStreamAsyncAwait(
service.getDataAsync('test'),
1
);
expect(cachedResponseTry2).toEqual({ payload: 'test' });
/**
* response acquired from cache, so no incrementation on the service spy call counter is expected here
*/
expect(mockServiceCallSpy).toHaveBeenCalledTimes(1);
/**
* 1 millisecond delay added, so the async cache resolves
*/
const cachedResponse2 = _timedStreamAsyncAwait(
service.getDataAsync('test2'),
1
);
expect(cachedResponse2).toEqual(null);
/**
* no cache for 'test2', but service call was made so the spy counter is incremented
*/
expect(mockServiceCallSpy).toHaveBeenCalledTimes(2);
const cachedResponse3 = _timedStreamAsyncAwait(
service.getDataAsync('test3'),
1000
);
/**
* service call is made and waited out
*/
expect(cachedResponse3).toEqual({ payload: 'test3' });
/**
* this should return cached response, since the currently cached one should be 'test3'
* 1 millisecond delay added, so the async cache resolves
*/
const cachedResponse4 = _timedStreamAsyncAwait(
service.getDataAsync('test'),
1
);
expect(cachedResponse4).toEqual(null);
expect(mockServiceCallSpy).toHaveBeenCalledTimes(4);
});
it('return cached date up until the maxAge period has passed and then bail out to data source', () => {
jasmine.clock().mockDate();
const asyncFreshData = _timedStreamAsyncAwait(
service.getDataWithExpiration('test'),
1000
);
expect(asyncFreshData).toEqual({ payload: 'test' });
expect(mockServiceCallSpy).toHaveBeenCalledTimes(1);
const cachedResponse = _timedStreamAsyncAwait(
service.getDataWithExpiration('test')
);
/**
* service shouldn't be called and we should route directly to cache
*/
expect(mockServiceCallSpy).toHaveBeenCalledTimes(1);
expect(cachedResponse).toEqual({ payload: 'test' });
/**
* progress in time for 7501 ms, e.g - one millisecond after the maxAge would expire
*/
jasmine.clock().tick(7501);
/**
* no cache anymore, bail out to service call
*/
const cachedResponse2 = _timedStreamAsyncAwait(
service.getDataWithExpiration('test')
);
expect(cachedResponse2).toEqual(null);
expect(mockServiceCallSpy).toHaveBeenCalledTimes(2);
let asyncFreshDataAfterCacheBust = null;
service.getDataWithExpiration('test').subscribe(data => {
asyncFreshDataAfterCacheBust = data;
});
jasmine.clock().tick(1000);
expect(asyncFreshDataAfterCacheBust).toEqual({ payload: 'test' });
});
it('return cached data up until the maxAge period but renew the expiration if called within the period', () => {
jasmine.clock().mockDate();
const asyncFreshData = _timedStreamAsyncAwait(
service.getDataWithSlidingExpiration('test'),
1000
);
expect(asyncFreshData).toEqual({ payload: 'test' });
expect(mockServiceCallSpy).toHaveBeenCalledTimes(1);
const cachedResponse = _timedStreamAsyncAwait(
service.getDataWithSlidingExpiration('test')
);
expect(cachedResponse).toEqual({ payload: 'test' });
/**
* call count should still be one, since we rerouted to cache, instead of service call
*/
expect(mockServiceCallSpy).toHaveBeenCalledTimes(1);
/**
* travel through 3000ms of time
*/
jasmine.clock().tick(3000);
/**
* calling the method again should renew expiration for 7500 more milliseconds
*/
service.getDataWithSlidingExpiration('test').subscribe();
jasmine.clock().tick(4501);
/**
* this should have returned null, if the cache didnt renew
*/
const cachedResponse2 = _timedStreamAsyncAwait(
service.getDataWithSlidingExpiration('test')
);
expect(cachedResponse2).toEqual({ payload: 'test' });
/**
* call count is still one, because we renewed the cache 4501ms ago
*/
expect(mockServiceCallSpy).toHaveBeenCalledTimes(1);
/**
* expire cache, shouldn't renew since 7501 ms have ellapsed
*/
jasmine.clock().tick(7501);
const cachedResponse3 = _timedStreamAsyncAwait(
service.getDataWithSlidingExpiration('test')
);
/**
* cached has expired, request hasn't returned yet but still - the service was called
*/
expect(cachedResponse3).toEqual(null);
expect(mockServiceCallSpy).toHaveBeenCalledTimes(2);
});
it('return cached data for 5 unique requests, then should bail to data source', () => {
/**
* call the same endpoint with 5 different parameters and cache all 5 responses, based on the maxCacheCount parameter
*/
const parameters = ['test1', 'test2', 'test3', 'test4', 'test5'];
parameters.forEach(async param =>
_timedStreamAsyncAwait(service.getDataWithMaxCacheCount(param), 1000)
);
/**
* data for all endpoints should be available through cache by now
*/
expect(mockServiceCallSpy).toHaveBeenCalledTimes(5);
const cachedResponse = _timedStreamAsyncAwait(
service.getDataWithMaxCacheCount('test1')
);
expect(cachedResponse).toEqual({ payload: 'test1' });
/** call count still 5 */
expect(mockServiceCallSpy).toHaveBeenCalledTimes(5);
/**
* this should return a maximum of 5 different cached responses
*/
const cachedResponseAll = _timedStreamAsyncAwait(
forkJoin(parameters.map(param => service.getDataWithMaxCacheCount(param)))
);
expect(cachedResponseAll).toEqual([
{ payload: 'test1' },
{ payload: 'test2' },
{ payload: 'test3' },
{ payload: 'test4' },
{ payload: 'test5' }
]);
/** call count still 5 */
expect(mockServiceCallSpy).toHaveBeenCalledTimes(5);
const asyncData = _timedStreamAsyncAwait(
service.getDataWithMaxCacheCount('test6'),
1000
);
expect(asyncData).toEqual({ payload: 'test6' });
/** call count incremented by one */
expect(mockServiceCallSpy).toHaveBeenCalledTimes(6);
/**
* by now the response for test6 should be cached and the one for test1 should be free for GC..
*/
const newParameters = ['test2', 'test3', 'test4', 'test5', 'test6'];
/**
* this should return a maximum of 5 different cached responses, with the latest one in the end
*/
const cachedResponseAll2 = _timedStreamAsyncAwait(
forkJoin(
newParameters.map(param => service.getDataWithMaxCacheCount(param))
),
1000
);
expect(cachedResponseAll2).toEqual([
{ payload: 'test2' },
{ payload: 'test3' },
{ payload: 'test4' },
{ payload: 'test5' },
{ payload: 'test6' }
]);
/** no service calls will be made, since we have all the responses still cached even after 1s (1000ms) */
expect(mockServiceCallSpy).toHaveBeenCalledTimes(6);
/**
* fetch and cache the test7 response
*/
const nonCachedResponse = _timedStreamAsyncAwait(
service.getDataWithMaxCacheCount('test7'),
1000
);
expect(nonCachedResponse).toEqual({ payload: 'test7' });
expect(mockServiceCallSpy).toHaveBeenCalledTimes(7);
/**
* since the cached response for 'test2' was now removed from cache by 'test7', it shouldn't be available in cache
*/
const cachedResponse2 = _timedStreamAsyncAwait(
service.getDataWithMaxCacheCount('test2')
);
expect(cachedResponse2).toEqual(null);
/**
* service call is made anyway
*/
expect(mockServiceCallSpy).toHaveBeenCalledTimes(8);
});
it('return cached data for 5 unique requests all available for 7500ms', () => {
jasmine.clock().mockDate();
/**
* call the same endpoint with 5 different parameters and cache all 5 responses, based on the maxCacheCount parameter
*/
const parameters = ['test1', 'test2', 'test3', 'test4', 'test5'];
parameters.forEach(param =>
service.getDataWithMaxCacheCountAndExpiration(param).subscribe()
);
expect(mockServiceCallSpy).toHaveBeenCalledTimes(5);
jasmine.clock().tick(1000);
const cachedResponse2 = _timedStreamAsyncAwait(
forkJoin(
parameters.map(param =>
service.getDataWithMaxCacheCountAndExpiration(param)
)
)
);
expect(mockServiceCallSpy).toHaveBeenCalledTimes(5);
expect(cachedResponse2).toEqual([
{ payload: 'test1' },
{ payload: 'test2' },
{ payload: 'test3' },
{ payload: 'test4' },
{ payload: 'test5' }
]);
/**
* expire caches
*/
jasmine.clock().tick(7501);
const cachedResponse3 = _timedStreamAsyncAwait(
service.getDataWithMaxCacheCountAndExpiration('test1')
);
expect(cachedResponse3).toEqual(null);
/**
* by now, no cache exists for the 'test1' parameter, so 1 more call will be made to the service
*/
expect(mockServiceCallSpy).toHaveBeenCalledTimes(6);
});
it('return cached data for 5 unique requests all available for 7500ms WITH slidingExpiration on', () => {
jasmine.clock().mockDate();
/**
* call the same endpoint with 5 different parameters and cache all 5 responses, based on the maxCacheCount parameter
*/
const parameters = ['test1', 'test2', 'test3', 'test4', 'test5'];
parameters.forEach(param =>
service.getDataWithMaxCacheCountAndSlidingExpiration(param).subscribe()
);
expect(mockServiceCallSpy).toHaveBeenCalledTimes(5);
/**
* allow for the mock request to complete
*/
jasmine.clock().tick(1000);
/**
* pass through time to just before the cache expires
*/
jasmine.clock().tick(7500);
/**
* re-call just with test2 so we renew its expiration
*/
service.getDataWithMaxCacheCountAndSlidingExpiration('test2').subscribe();
expect(mockServiceCallSpy).toHaveBeenCalledTimes(5);
/**
* expire ALL caches except the test2 one
*/
jasmine.clock().tick(1);
const cachedResponse = _timedStreamAsyncAwait(
combineLatest(
parameters.map(param =>
service
.getDataWithMaxCacheCountAndSlidingExpiration(param)
.pipe(startWith(null))
)
)
);
/**
* no cache for 4 payloads, so 4 more calls to the service will be made
*/
expect(mockServiceCallSpy).toHaveBeenCalledTimes(9);
expect(cachedResponse).toEqual([
null,
{ payload: 'test2' },
null,
null,
null
]);
jasmine.clock().uninstall();
});
it('return cached data up until new parameters are passed WITH a custom resolver function', () => {
const asyncFreshData = _timedStreamAsyncAwait(
service.getDataWithCustomCacheResolver('test1'),
1000
);
expect(asyncFreshData).toEqual({ payload: 'test1' });
expect(mockServiceCallSpy).toHaveBeenCalled();
const asyncFreshData2 = _timedStreamAsyncAwait(
service.getDataWithCustomCacheResolver('test2'),
1000
);
expect(asyncFreshData2).toEqual({ payload: 'test2' });
expect(mockServiceCallSpy).toHaveBeenCalledTimes(2);
const cachedResponse = _timedStreamAsyncAwait(
service.getDataWithCustomCacheResolver('test3', {
straightToLastCache: true
})
);
expect(cachedResponse).toEqual({ payload: 'test2' });
/**
* call count still 2, since we rerouted directly to cache
*/
expect(mockServiceCallSpy).toHaveBeenCalledTimes(2);
_timedStreamAsyncAwait(service.getDataWithCustomCacheResolver('test3'));
/**no cache reerouter -> bail to service call -> increment call counter*/
expect(mockServiceCallSpy).toHaveBeenCalledTimes(3);
});
it('only cache data when a specific response is returned, otherwise it should bail to service call', () => {
const asyncData = _timedStreamAsyncAwait(
service.getDataWithCustomCacheDecider('test1'),
1000
);
expect(asyncData).toEqual({ payload: 'test1' });
expect(mockServiceCallSpy).toHaveBeenCalledTimes(1);
/**
* this call shouldn't be cached, since the custom response decider hasn't passed
*/
const cachedData = _timedStreamAsyncAwait(
service.getDataWithCustomCacheDecider('test1')
);
expect(cachedData).toEqual(null);
expect(mockServiceCallSpy).toHaveBeenCalledTimes(2);
/**
* next calls will be for 'test' whose response will match the cache deciders condition and it will be cached
*/
const asyncData2 = _timedStreamAsyncAwait(
service.getDataWithCustomCacheDecider('test'),
1000
);
expect(asyncData2).toEqual({ payload: 'test' });
expect(mockServiceCallSpy).toHaveBeenCalledTimes(3);
/**
* this call has to return cached data, since we the response cache decider should have matched the previous one
*/
const cachedData2 = _timedStreamAsyncAwait(
service.getDataWithCustomCacheDecider('test')
);
expect(cachedData2).toEqual({ payload: 'test' });
/**
* the service call count won't be incremented
*/
expect(mockServiceCallSpy).toHaveBeenCalledTimes(3);
});
it('cache data until the cacheBusterNotifier has emitted', () => {
const asyncFreshData = _timedStreamAsyncAwait(
service.getDataWithCacheBusting('test'),
1000
);
expect(asyncFreshData).toEqual({ payload: 'test' });
expect(mockServiceCallSpy).toHaveBeenCalledTimes(1);
const cachedResponse = _timedStreamAsyncAwait(
service.getDataWithCacheBusting('test')
);
expect(cachedResponse).toEqual({ payload: 'test' });
/**
* response acquired from cache, so no incrementation on the service spy call counter is expected here
*/
expect(mockServiceCallSpy).toHaveBeenCalledTimes(1);
/**
* make the save call
* after 1 second the cache busting subject will emit and the cache for getDataWithCacheBusting('test') will be relieved of
*/
expect(
_timedStreamAsyncAwait(service.saveDataAndCacheBust(), 1000)
).toEqual('SAVED');
const cachedResponse2 = _timedStreamAsyncAwait(
service.getDataWithCacheBusting('test')
);
expect(cachedResponse2).toEqual(null);
/**
* call count has incremented due to the actual method call (instead of cache)
*/
expect(mockServiceCallSpy).toHaveBeenCalledTimes(2);
/**
* pass through 1s of time
*/
jasmine.clock().tick(1000);
/**
* synchronous cached response should now be returned
*/
expect(
_timedStreamAsyncAwait(service.getDataWithCacheBusting('test'))
).toEqual({ payload: 'test' });
});
});
function _timedStreamAsyncAwait(stream$: Observable<any>, skipTime?: number) {
let response = null;
stream$.subscribe(data => {
response = data;
});
if (skipTime) {
/**
* use jasmine clock to artificially manipulate time-based web apis like setTimeout, setInterval and Date
* we can easily use async/await but that means that we will have to actually wait out the time needed for every delay/mock request
* we can't use fakeAsync/tick here since this is Angular agnostic test and we do not need zonejs or change detection
*/
jasmine.clock().tick(skipTime);
}
return response;
}