Skip to content

Commit

Permalink
feat(cache-manager): allow @CacheTTL at the controller level
Browse files Browse the repository at this point in the history
  • Loading branch information
quangtran88 committed Jul 16, 2023
1 parent 64b5582 commit b641e22
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 1 deletion.
4 changes: 3 additions & 1 deletion lib/interceptors/cache.interceptor.ts
Expand Up @@ -54,7 +54,9 @@ export class CacheInterceptor implements NestInterceptor {
): Promise<Observable<any>> {
const key = this.trackBy(context);
const ttlValueOrFactory =
this.reflector.get(CACHE_TTL_METADATA, context.getHandler()) ?? null;
this.reflector.get(CACHE_TTL_METADATA, context.getHandler()) ??
this.reflector.get(CACHE_TTL_METADATA, context.getClass()) ??
null;

if (!key) {
return next.handle();
Expand Down
12 changes: 12 additions & 0 deletions tests/e2e/custom-ttl.spec.ts
Expand Up @@ -29,6 +29,18 @@ describe('Caching Custom TTL', () => {
await request(server).get('/').expect(200, '0');
});

it('should return a different value after the TTL of the controller is elapsed', async () => {
await request(server).get('/controller').expect(200, '0');
await new Promise(resolve => setTimeout(resolve, 600));
await request(server).get('/controller').expect(200, '1');
});

it('should return the cached value within the TTL of the controller', async () => {
await request(server).get('/controller').expect(200, '0');
await new Promise(resolve => setTimeout(resolve, 300));
await request(server).get('/controller').expect(200, '0');
});

afterEach(async () => {
await app.close();
});
Expand Down
7 changes: 7 additions & 0 deletions tests/src/custom-ttl/custom-ttl.controller.ts
Expand Up @@ -2,6 +2,7 @@ import { Controller, Get, UseInterceptors } from '@nestjs/common';
import { CacheInterceptor, CacheTTL } from '../../../lib';

@Controller()
@CacheTTL(600)
export class CustomTtlController {
counter = 0;
constructor() {}
Expand All @@ -12,4 +13,10 @@ export class CustomTtlController {
getNumber() {
return this.counter++;
}

@Get('/controller')
@UseInterceptors(CacheInterceptor)
getNumberWithControllerTTL() {
return this.counter++;
}
}

0 comments on commit b641e22

Please sign in to comment.