Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(cache-manager): allow @CacheTTL at the controller level #112

Merged
merged 1 commit into from
Jul 17, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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++;
}
}