diff --git a/packages/api/routes/conversations.ts b/packages/api/routes/conversations.ts index 2c49e89..717d79f 100644 --- a/packages/api/routes/conversations.ts +++ b/packages/api/routes/conversations.ts @@ -23,10 +23,11 @@ export default function getConversationRoutes() { router.get('/:conversationId', authCheck); // get all conversations that I am in + // todo: add in pagination for performance, while allowing getting long polling updates? router.get('/', authCheck, getAllConversations); // get a one on one conversation based on other user Id - router.get('/check/:otherUserId', authCheck); + router.get('/check/:otherUserId', authCheck, getOneOnOneConversationIfExists); // get a conversation's content router.get('/:conversationId/content', authCheck); @@ -40,6 +41,8 @@ export default function getConversationRoutes() { const getAllConversations = async (req: Request, res: Response, next: NextFunction) => { const userInfo = res.locals.userInfo as JwtClaims; + // todo: use pagination params to get only certain ones + try { const resultConversations = await ConversationService.getAllConversationsForUser( userInfo.userId, @@ -57,6 +60,28 @@ const getAllConversations = async (req: Request, res: Response, next: NextFuncti } }; +const getOneOnOneConversationIfExists = async (req: Request, res: Response, next: NextFunction) => { + const userInfo = res.locals.userInfo as JwtClaims; + const { otherUserId } = req.params; + + try { + const resultConversation = await ConversationService.getConversationBetweenTwoPeople( + new ObjectId(userInfo.userId), + new ObjectId(otherUserId), + ); + + return res.json( + new NirvanaResponse( + resultConversation?._id ?? undefined, + undefined, + 'here is the conversation if it exists', + ), + ); + } catch (error) { + return next(Error('unable to get conversations')); + } +}; + const createConversation = async (req: Request, res: Response, next: NextFunction) => { const createRequest = req.body as CreateConversationRequest; const userInfo = res.locals.userInfo as JwtClaims; diff --git a/packages/api/services/conversation.service.ts b/packages/api/services/conversation.service.ts index 4bd17b6..06463c2 100644 --- a/packages/api/services/conversation.service.ts +++ b/packages/api/services/conversation.service.ts @@ -28,4 +28,27 @@ export default class ConversationService { return undefined; } + + /** + * gets one on one conversation between two people if it exists + */ + static async getConversationBetweenTwoPeople(userAId: ObjectId, userBId: ObjectId) { + const query = { + $and: [ + { + 'members._id': userAId, + }, + { 'members._id': userBId }, + ], + }; + + const res = await collections.conversations?.findOne(query); + + // exists + if (res?._id) { + return res as Conversation; + } + + return null; + } }