@@ -40,11 +40,10 @@ router.get(
4040 query . contact_id = contact_id
4141 }
4242
43- // Optimize query with field selection
4443 const conversations = await Conversation . find ( query )
4544 . select ( '_id agent_id company_id contact_id user_id channel status started_at ended_at tags metadata created_at updated_at' )
4645 . sort ( { started_at : - 1 } )
47- . limit ( Math . min ( Number ( limit ) , 50 ) ) // Cap at 50 for performance
46+ . limit ( Math . min ( Number ( limit ) , 50 ) )
4847 . skip ( Number ( offset ) )
4948 . lean ( )
5049
@@ -106,7 +105,7 @@ router.get(
106105 try {
107106 const { id } = req . params
108107 const companyId = req . user ! . company_id !
109- const limit = Math . min ( Number ( req . query . limit ) || 50 , 100 ) // Cap at 100 for performance
108+ const limit = Math . min ( Number ( req . query . limit ) || 50 , 100 )
110109 const offset = Number ( req . query . offset ) || 0
111110 const threadId = req . query . thread_id as string | undefined
112111
@@ -146,24 +145,18 @@ router.get(
146145 query . thread_id = { $exists : false }
147146 }
148147
149- // Query messages with field selection for better performance
150- // For pagination: we want to load from newest to oldest (descending)
151- // Then reverse to show oldest first in UI
152- // offset=0 gets newest messages, offset=20 gets next 20 older messages
153148 const messages = await Message . find ( query )
154149 . select ( '_id conversation_id thread_id sender_type role content message_type attachments ai_metadata metadata created_at' )
155- . sort ( { created_at : - 1 } ) // Newest first
150+ . sort ( { created_at : - 1 } )
156151 . limit ( limit )
157152 . skip ( offset )
158153 . lean ( )
159154
160- // Reverse to show chronological order (oldest first) in UI
161155 messages . reverse ( )
162156
163157 const total = await Message . countDocuments ( query )
164158
165- // Cache result with longer TTL for better performance
166- await setCache ( cacheKey , { messages, total } , 120 ) // 2 minute cache
159+ await setCache ( cacheKey , { messages, total } , 120 )
167160
168161 res . json ( {
169162 messages,
0 commit comments