@@ -2,7 +2,7 @@ import { Request, Response } from "express";
22import { db , roomsTable , roomParticipantsTable , chatsTable , drawsTable , usersTable } from "@workspace/db/client" ;
33import { random } from "../utils" ;
44import { JoinRoomSchema } from "@workspace/common" ;
5- import { eq , desc } from "drizzle-orm" ;
5+ import { eq , desc , and } from "drizzle-orm" ;
66
77export async function createRoomController ( req : Request , res : Response ) {
88 try {
@@ -75,6 +75,21 @@ export async function joinRoomController(req: Request, res: Response) {
7575 return ;
7676 }
7777
78+ const existingParticipation = await db . select ( )
79+ . from ( roomParticipantsTable )
80+ . where ( and (
81+ eq ( roomParticipantsTable . roomId , room . id ) ,
82+ eq ( roomParticipantsTable . userId , userId )
83+ ) ) ;
84+
85+ if ( existingParticipation . length > 0 ) {
86+ res . json ( {
87+ message : "Room Joined Successfully" ,
88+ room,
89+ } ) ;
90+ return ;
91+ }
92+
7893 // Insert into participants
7994 try {
8095 await db . insert ( roomParticipantsTable ) . values ( {
@@ -133,8 +148,15 @@ export async function fetchAllRoomsController(req: Request, res: Response) {
133148 . where ( eq ( roomParticipantsTable . userId , userId ) )
134149 . orderBy ( desc ( roomsTable . createdAt ) ) ;
135150
136- // For each room, fetch latest Chat and Draw
137- const roomsWithDetails = await Promise . all ( userRooms . map ( async ( room ) => {
151+ const uniqueUserRoomsMap = new Map ( ) ;
152+ userRooms . forEach ( room => {
153+ if ( ! uniqueUserRoomsMap . has ( room . id ) ) {
154+ uniqueUserRoomsMap . set ( room . id , room ) ;
155+ }
156+ } ) ;
157+ const uniqueUserRooms = Array . from ( uniqueUserRoomsMap . values ( ) ) ;
158+
159+ const roomsWithDetails = await Promise . all ( uniqueUserRooms . map ( async ( room ) => {
138160 const latestChat = await db . select ( {
139161 content : chatsTable . content ,
140162 createdAt : chatsTable . createdAt ,
@@ -145,7 +167,7 @@ export async function fetchAllRoomsController(req: Request, res: Response) {
145167 . from ( chatsTable )
146168 . innerJoin ( usersTable , eq ( chatsTable . userId , usersTable . id ) )
147169 . where ( eq ( chatsTable . roomId , room . id ) )
148- . orderBy ( desc ( chatsTable . serialNumber ) ) // serialNumber is auto inc
170+ . orderBy ( desc ( chatsTable . serialNumber ) )
149171 . limit ( 1 ) ;
150172
151173 const latestDraws = await db . select ( )
0 commit comments