Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion lib/decorators/cache-key.decorator.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
import { ExecutionContext, SetMetadata } from '@nestjs/common';
import { CACHE_KEY_METADATA } from '../cache.constants';

export type CacheKeyFactory = (ctx: ExecutionContext) => string;
export type CacheKeyFactory = (
ctx: ExecutionContext,
) => string | Promise<string | undefined> | undefined;

/**
* Decorator that sets the caching key used to store/retrieve cached items for
Expand Down
20 changes: 15 additions & 5 deletions lib/interceptors/cache.interceptor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ export class CacheInterceptor implements NestInterceptor {
context: ExecutionContext,
next: CallHandler,
): Promise<Observable<any>> {
const key = this.trackBy(context);
const key = await this.trackBy(context);
const ttlValueOrFactory: number | CacheTTLFactory | null =
this.reflector.get(CACHE_TTL_METADATA, context.getHandler()) ??
this.reflector.get(CACHE_TTL_METADATA, context.getClass()) ??
Expand Down Expand Up @@ -88,16 +88,26 @@ export class CacheInterceptor implements NestInterceptor {
}
}

protected trackBy(context: ExecutionContext): string | undefined {
protected async trackBy(
context: ExecutionContext,
): Promise<string | undefined | null> {
const httpAdapter = this.httpAdapterHost.httpAdapter;
const isHttpApp = httpAdapter && !!httpAdapter.getRequestMethod;
const cacheMetadataOrFactory: string | CacheKeyFactory | null =
this.reflector.get(CACHE_KEY_METADATA, context.getHandler()) ?? null;

if (!isHttpApp || cacheMetadataOrFactory) {
return isFunction(cacheMetadataOrFactory)
? cacheMetadataOrFactory(context)
: cacheMetadataOrFactory;
if (isFunction(cacheMetadataOrFactory)) {
const cacheKey = cacheMetadataOrFactory(context);

if (typeof cacheKey === 'object' && isFunction(cacheKey['then'])) {
return await cacheKey;
Comment thread
swieton marked this conversation as resolved.
} else {
return cacheKey;
}
} else {
return cacheMetadataOrFactory;
}
}

const request = context.getArgByIndex(0);
Expand Down