Skip to content

Commit ff43278

Browse files
committed
implement search endpoint
1 parent 7f0847d commit ff43278

File tree

1 file changed

+40
-1
lines changed

1 file changed

+40
-1
lines changed

src/nylas/router.py

Lines changed: 40 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -85,7 +85,7 @@ async def fetch_emails(
8585
),
8686
) -> List[Dict[str, Any]]:
8787
"""
88-
Retrieve the first 5 threads of the authenticated account from the Nylas API.
88+
Retrieve the first 20 threads of the authenticated account from the Nylas API.
8989
"""
9090
from src.main import (
9191
code_app,
@@ -295,3 +295,42 @@ async def read_contacts(
295295

296296
# todo
297297
return []
298+
299+
300+
@router.get(
301+
"/nylas/search-emails",
302+
response_model=List[Dict[str, Any]],
303+
status_code=200,
304+
name="nylas:search-emails",
305+
)
306+
async def search_emails(
307+
search: str,
308+
current_user: users_schemas.UserObjectSchema = Depends(
309+
dependencies.get_current_user
310+
),
311+
) -> List[Dict[str, Any]]:
312+
"""
313+
Retrieve the seached emails threads of the authenticated account from the Nylas API.
314+
"""
315+
from src.main import (
316+
code_app,
317+
)
318+
319+
# A workaround to retrieve threads associated with discovered messages because the
320+
# `messages.search(search, limit=20)` method returns individual messages, not threads.
321+
# Therefore, we iterate through the threads and select the ones containing message IDs.
322+
threads = code_app.state.nylas.threads.where(
323+
limit=20, view="expanded"
324+
).all()
325+
messages = code_app.state.nylas.messages.search(search, limit=20)
326+
message_ids = set(message["id"] for message in messages)
327+
# Filter threads that contain at least one message from the list of messages
328+
threads_with_messages = [
329+
thread
330+
for thread in threads
331+
if any(message["id"] in message_ids for message in thread["_messages"])
332+
]
333+
res_json = [
334+
item.as_json(enforce_read_only=False) for item in threads_with_messages
335+
]
336+
return res_json

0 commit comments

Comments
 (0)