프로젝트에 Nest CLI를 사용해 레디스 모듈을 생성합니다.
$ nest g mo redis
그리고 모듈에 캐시 모듈을 동적으로 주입 합니다.
import { CacheModule, Module } from '@nestjs/common';
import { ConfigModule, ConfigService } from '@nestjs/config';
import * as redisStore from 'cache-manager-redis-store';
@Module({
imports: [
CacheModule.registerAsync({
imports: [ConfigModule],
inject: [ConfigService],
useFactory: async (configService: ConfigService) => ({
store: redisStore,
host: configService.get('REDIS_HOST'),
port: configService.get('REDIS_PORT'),
ttl: configService.get('REDIS_TTL'),
}),
isGlobal: true,
}),
],
})
export class RedisModule {}
이제 레디스를 사용할 준비가 완료 되었습니다.
레디스를 따로 레포지토리 레이어로 구현해도 되지만, 필요한 서비스에 캐시 매니저를 주입해서 사용해도 됩니다.
캐싱이 필요한 서비스 레이어에 캐시 매니저를 주입합니다.
import { Cache } from 'cache-manager';
@Injectable()
export class AuthService {
constructor(
...
@Inject(CACHE_MANAGER) private cacheManager: Cache,
) {}
간단한 회원 정보 로직입니다.
회원 로그인 시 패스워드 일치 여부를 확인하고, 캐싱되어 있는 정보가 있는지 확인한 후 캐싱 되어 있다면 캐싱된 정보를 보내주고 아니라면 캐싱 후 회원 정보를 보내줍니다.
const cacheData = await this.cacheManager.get(user.id);
if (isMatch && cacheData) return cacheData;
if (isMatch && !cacheData) {
await this.cacheManager.set(user.id, user);
return user;
}
'개발 공부 > NestJS' 카테고리의 다른 글
Multer를 사용해 ImgBB에 이미지 올리기 (0) | 2023.04.05 |
---|---|
JWT Guard 에러 메세지 커스텀 (0) | 2023.04.03 |
인 메모리 데이터베이스, Redis (1편) (0) | 2023.03.26 |
Serialize 직렬화 (0) | 2023.03.23 |
인터셉터 Interceptor (0) | 2023.03.19 |