File tree Expand file tree Collapse file tree 3 files changed +40
-13
lines changed
Expand file tree Collapse file tree 3 files changed +40
-13
lines changed Original file line number Diff line number Diff line change 11import { Module } from '@nestjs/common' ;
2+ import { ConfigModule , ConfigService } from '@nestjs/config' ;
23import { RedisService } from './redis.service' ;
4+ import Redis from 'ioredis' ;
5+
6+ // 의존성 주입할 때 redis client를 식별할 토큰
7+ const REDIS_CLIENT_TOKEN = 'REDIS_CLIENT' ;
38
49@Module ( {
5- providers : [ RedisService ] ,
6- exports : [ RedisService ] ,
10+ imports : [ ConfigModule ] , // ConfigModule 추가
11+ providers : [
12+ RedisService ,
13+ {
14+ provide : REDIS_CLIENT_TOKEN ,
15+ inject : [ ConfigService ] , // ConfigService 주입
16+ useFactory : ( configService : ConfigService ) => {
17+ return new Redis ( {
18+ host : configService . get < string > ( 'REDIS_HOST' ) ,
19+ port : configService . get < number > ( 'REDIS_PORT' ) ,
20+ } ) ;
21+ } ,
22+ } ,
23+ ] ,
24+ exports : [ RedisService , REDIS_CLIENT_TOKEN ] ,
725} )
826export class RedisModule { }
Original file line number Diff line number Diff line change 11import { Test , TestingModule } from '@nestjs/testing' ;
22import { RedisService } from './redis.service' ;
3+ const REDIS_CLIENT_TOKEN = 'REDIS_CLIENT' ;
34
45describe ( 'RedisService' , ( ) => {
56 let service : RedisService ;
7+ const mockRedisClient = {
8+ set : jest . fn ( ) ,
9+ get : jest . fn ( ) ,
10+ quit : jest . fn ( ) ,
11+ } ;
612
713 beforeEach ( async ( ) => {
814 const module : TestingModule = await Test . createTestingModule ( {
9- providers : [ RedisService ] ,
15+ providers : [
16+ RedisService ,
17+ {
18+ provide : REDIS_CLIENT_TOKEN ,
19+ useValue : mockRedisClient ,
20+ } ,
21+ ] ,
1022 } ) . compile ( ) ;
1123
1224 service = module . get < RedisService > ( RedisService ) ;
Original file line number Diff line number Diff line change 11import { Injectable } from '@nestjs/common' ;
2+ import { Inject } from '@nestjs/common' ;
23import Redis from 'ioredis' ;
4+ const REDIS_CLIENT_TOKEN = 'REDIS_CLIENT' ;
5+
36type RedisPage = {
47 title : string ;
58 content : string ;
69} ;
710@Injectable ( )
811export class RedisService {
9- private readonly redisClient : Redis ;
12+ // private readonly redisClient: Redis;
1013
11- constructor ( ) {
12- console . log ( '====================' ) ;
13- console . log ( process . env . REDIS_HOST ) ;
14- console . log ( process . env . REDIS_PORT ) ;
15- this . redisClient = new Redis ( {
16- host : process . env . REDIS_HOST ,
17- port : parseInt ( process . env . REDIS_PORT ) ,
18- } ) ;
19- }
14+ constructor (
15+ @Inject ( REDIS_CLIENT_TOKEN ) private readonly redisClient : Redis ,
16+ ) { }
2017
2118 async getAllKeys ( ) {
2219 return await this . redisClient . keys ( '*' ) ;
You can’t perform that action at this time.
0 commit comments