@@ -8,9 +8,12 @@ import { Equal, FindOptionsWhere, Repository } from 'typeorm';
88import { User } from '../users/entities/user.entity' ;
99import { ChatMessage } from './entities/chat-message.entity' ;
1010import { Room } from './entities/room.entity' ;
11+ import * as NodeCache from 'node-cache' ;
1112
1213@Injectable ( )
1314export class ChatService {
15+ private cache : NodeCache ;
16+
1417 constructor (
1518 @InjectRepository ( ChatMessage )
1619 private chatRepository : Repository < ChatMessage > ,
@@ -20,13 +23,23 @@ export class ChatService {
2023
2124 @InjectRepository ( Room )
2225 private roomRepository : Repository < Room >
23- ) { }
26+ ) {
27+ // Initialize cache with 5 minute TTL
28+ this . cache = new NodeCache ( { stdTTL : 300 } ) ;
29+ }
2430
2531 async getUserById ( id : string ) : Promise < User > {
32+ // Try to get from cache first
33+ const cachedUser = this . cache . get < User > ( `user:${ id } ` ) ;
34+ if ( cachedUser ) return cachedUser ;
35+
2636 const user = await this . userRepository . findOne ( { where : { id } } ) ;
2737 if ( ! user ) {
2838 throw new NotFoundException ( `User with ID ${ id } not found` ) ;
2939 }
40+
41+ // Store in cache
42+ this . cache . set ( `user:${ id } ` , user ) ;
3043 return user ;
3144 }
3245
@@ -134,12 +147,20 @@ export class ChatService {
134147 }
135148
136149 async findRoomBetweenUsers ( user1 : User , user2 : User ) : Promise < Room | null > {
150+ const cacheKey = `room:${ user1 . id } :${ user2 . id } ` ;
151+ const cachedRoom = this . cache . get < Room > ( cacheKey ) ;
152+ if ( cachedRoom ) return cachedRoom ;
153+
137154 const room = await this . roomRepository . findOne ( {
138155 where : [
139156 { employer : Equal ( user1 . id ) , freelancer : Equal ( user2 . id ) } ,
140157 { employer : Equal ( user2 . id ) , freelancer : Equal ( user1 . id ) } ,
141158 ] ,
142159 } ) ;
160+
161+ if ( room ) {
162+ this . cache . set ( cacheKey , room ) ;
163+ }
143164 return room || null ;
144165 }
145166
0 commit comments