Skip to content

Commit ffcb5ac

Browse files
Merge pull request #112 from quangtran88/feat/controller-cache-ttl
feat(cache-manager): allow @CacheTTL at the controller level
2 parents 64b5582 + b641e22 commit ffcb5ac

File tree

3 files changed

+22
-1
lines changed

3 files changed

+22
-1
lines changed

lib/interceptors/cache.interceptor.ts

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -54,7 +54,9 @@ export class CacheInterceptor implements NestInterceptor {
5454
): Promise<Observable<any>> {
5555
const key = this.trackBy(context);
5656
const ttlValueOrFactory =
57-
this.reflector.get(CACHE_TTL_METADATA, context.getHandler()) ?? null;
57+
this.reflector.get(CACHE_TTL_METADATA, context.getHandler()) ??
58+
this.reflector.get(CACHE_TTL_METADATA, context.getClass()) ??
59+
null;
5860

5961
if (!key) {
6062
return next.handle();

tests/e2e/custom-ttl.spec.ts

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,18 @@ describe('Caching Custom TTL', () => {
2929
await request(server).get('/').expect(200, '0');
3030
});
3131

32+
it('should return a different value after the TTL of the controller is elapsed', async () => {
33+
await request(server).get('/controller').expect(200, '0');
34+
await new Promise(resolve => setTimeout(resolve, 600));
35+
await request(server).get('/controller').expect(200, '1');
36+
});
37+
38+
it('should return the cached value within the TTL of the controller', async () => {
39+
await request(server).get('/controller').expect(200, '0');
40+
await new Promise(resolve => setTimeout(resolve, 300));
41+
await request(server).get('/controller').expect(200, '0');
42+
});
43+
3244
afterEach(async () => {
3345
await app.close();
3446
});

tests/src/custom-ttl/custom-ttl.controller.ts

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ import { Controller, Get, UseInterceptors } from '@nestjs/common';
22
import { CacheInterceptor, CacheTTL } from '../../../lib';
33

44
@Controller()
5+
@CacheTTL(600)
56
export class CustomTtlController {
67
counter = 0;
78
constructor() {}
@@ -12,4 +13,10 @@ export class CustomTtlController {
1213
getNumber() {
1314
return this.counter++;
1415
}
16+
17+
@Get('/controller')
18+
@UseInterceptors(CacheInterceptor)
19+
getNumberWithControllerTTL() {
20+
return this.counter++;
21+
}
1522
}

0 commit comments

Comments
 (0)