diff --git a/lib/interceptors/cache.interceptor.ts b/lib/interceptors/cache.interceptor.ts index 1750894..bc59a3c 100644 --- a/lib/interceptors/cache.interceptor.ts +++ b/lib/interceptors/cache.interceptor.ts @@ -54,7 +54,9 @@ export class CacheInterceptor implements NestInterceptor { ): Promise> { 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(); diff --git a/tests/e2e/custom-ttl.spec.ts b/tests/e2e/custom-ttl.spec.ts index 08c79b4..25e8f66 100644 --- a/tests/e2e/custom-ttl.spec.ts +++ b/tests/e2e/custom-ttl.spec.ts @@ -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(); }); diff --git a/tests/src/custom-ttl/custom-ttl.controller.ts b/tests/src/custom-ttl/custom-ttl.controller.ts index bbf671a..cd641b1 100644 --- a/tests/src/custom-ttl/custom-ttl.controller.ts +++ b/tests/src/custom-ttl/custom-ttl.controller.ts @@ -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() {} @@ -12,4 +13,10 @@ export class CustomTtlController { getNumber() { return this.counter++; } + + @Get('/controller') + @UseInterceptors(CacheInterceptor) + getNumberWithControllerTTL() { + return this.counter++; + } }