cache-manager icon indicating copy to clipboard operation
cache-manager copied to clipboard

HTTP Headers HIT/MISS con Caching

Open setterlee opened this issue 1 year ago • 1 comments
trafficstars

Is there an existing issue that is already proposing this?

  • [X] I have searched the existing issues

Is your feature request related to a problem? Please describe it

I started to use the in-memory caching in a REST api that I'm working and I noticed that this feature don't include any information that tells if a response come from cache or the provider. I was specting a header with this info.

Describe the solution you'd like

Include a header manage on the CacheInterceptor that tells if the response comes from the cache or de provider.

Teachability, documentation, adoption, migration strategy

I Developed this Custom Interceptor to address this by the moment:

import { ExecutionContext, Injectable, CallHandler } from '@nestjs/common';
import { Observable, of } from 'rxjs';
import { tap } from 'rxjs/operators';
import { CacheInterceptor } from '@nestjs/cache-manager';


@Injectable()
export class CustomCacheInterceptor extends CacheInterceptor {
  async intercept(context: ExecutionContext, next: CallHandler): Promise<Observable<any>> {
    const key = this.trackBy(context);
    if (!key) {
      return next.handle();
    }

    const cacheManager = this.cacheManager;
    const cachedResponse = await cacheManager.get(key);
    
    if (cachedResponse) {
      const response = context.switchToHttp().getResponse();
      response.setHeader('X-Cache-Status', 'HIT');
      return of(cachedResponse);
    }

    return next.handle().pipe(
      tap(async (response) => {
        const httpResponse = context.switchToHttp().getResponse();
        httpResponse.setHeader('X-Cache-Status', 'MISS');
        await cacheManager.set(key, response);
      }),
    );
  }
}

What is the motivation / use case for changing the behavior?

I've working with other cache functionality in another platforms that include this behavior and helps a lot when any problem show up...

setterlee avatar Aug 14 '24 17:08 setterlee

Would you like to create a PR for this issue?

kamilmysliwiec avatar Aug 15 '24 09:08 kamilmysliwiec

https://github.com/nestjs/cache-manager/pull/527

kamilmysliwiec avatar Oct 21 '24 08:10 kamilmysliwiec