Last active
October 20, 2022 20:07
-
-
Save Akifcan/706cde53cb69c085531036d9b7f503f2 to your computer and use it in GitHub Desktop.
Cache interceptor
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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