Skip to content

Instantly share code, notes, and snippets.

@Akifcan
Last active October 20, 2022 20:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Akifcan/706cde53cb69c085531036d9b7f503f2 to your computer and use it in GitHub Desktop.
Save Akifcan/706cde53cb69c085531036d9b7f503f2 to your computer and use it in GitHub Desktop.
Cache interceptor
import {Injectable, NestInterceptor, ExecutionContext, CallHandler, Inject, Logger} from '@nestjs/common'
import {map, Observable, tap} from 'rxjs'
import {RedisService} from './redis.service'
@Injectable()
export class CacheInterceptor implements NestInterceptor {
@Inject() redisService: RedisService
async intercept(context: ExecutionContext, next: CallHandler): Promise<Observable<any>> {
if (process.env.NODE_ENV.includes('development')) {
Logger.log('CACHE WONT WORK IN DEV MODE')
return next.handle()
}
const request = context.switchToHttp().getRequest()
const key = request._parsedOriginalUrl?.path || request.path
const data = await this.redisService.get(key)
if (data) {
Logger.log('from cache')
return next.handle().pipe(map(() => data))
}
Logger.log('from db')
return next.handle().pipe(
tap(value => {
if (value) {
this.redisService.save(key, value)
}
}),
)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment