Skip to content

Commit

Permalink
Merge pull request #112 from quangtran88/feat/controller-cache-ttl
Browse files Browse the repository at this point in the history
feat(cache-manager): allow @CacheTTL at the controller level
  • Loading branch information
kamilmysliwiec authored Jul 17, 2023
2 parents 64b5582 + b641e22 commit ffcb5ac
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
Original file line number Diff line number Diff line change
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
Original file line number Diff line number Diff line change
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
Original file line number Diff line number Diff line change
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 ffcb5ac

Please sign in to comment.