import { CacheInterceptor } from '@nestjs/cache-manager';
import { ExecutionContext, Injectable } from '@nestjs/common';

/**
 * 扩展 CacheInterceptor，将 POST body 纳入 cache key，
 * 避免不同参数的请求命中同一份缓存。
 * cache key 格式：{url}:{JSON.stringify(body)}
 */
@Injectable()
export class HttpCacheInterceptor extends CacheInterceptor {
  trackBy(context: ExecutionContext): string | undefined {
    const request = context.switchToHttp().getRequest();
    const url = request.url as string;
    const body = request.body;

    const bodyKey =
      body && Object.keys(body).length > 0 ? JSON.stringify(body) : '';

    return bodyKey ? `${url}:${bodyKey}` : url;
  }
}
