file module import { CacheInterceptor , CallHandler , ExecutionContext , Injectable , RequestMethod } from '@nestjs/common' ; import { Observable , of } from 'rxjs' ; import { tap } from 'rxjs/operators' ; import * as APP_CONFIG from '../app.config' ; import * as META from '../common/constants/meta.constant' ; class classdesc @ Injectable ( ) export class HttpCacheInterceptor extends CacheInterceptor { async intercept ( context , next ) { const key = this . trackBy ( context ) ; const target = context . getHandler ( ) ; const metaTTL = this . reflector . get ( META . HTTP_CACHE_TTL_METADATA , target ) ; const ttl = metaTTL || APP_CONFIG . REDIS . defaultCacheTTL ; if ( ! key ) { return next . handle ( ) ; } try { const value = await this . cacheManager . get ( key ) ; return value ? of ( value ) : next . handle ( ) . pipe ( tap ( response => this . cacheManager . set ( key , response , { ttl } ) ) ) ; } catch ( error ) { return next . handle ( ) ; } } function description trackBy ( context ) { const request = context . switchToHttp ( ) . getRequest ( ) ; const httpServer = this . httpAdapterHost . httpAdapter ; const isHttpApp = httpServer && ! ! httpServer . getRequestMethod ; const isGetRequest = isHttpApp && httpServer . getRequestMethod ( request ) === RequestMethod [ RequestMethod . GET ] ; const requestUrl = httpServer . getRequestUrl ( request ) ; const cacheKey = this . reflector . get ( META . HTTP_CACHE_KEY_METADATA , context . getHandler ( ) ) ; const isMatchedCache = isHttpApp && isGetRequest && cacheKey ; return isMatchedCache ? cacheKey : undefined ; } }