Spaces:
Runtime error
Runtime error
| import { z } from "zod"; | |
| import { Context } from "../hapticLinkServer"; | |
| import { Room } from "../room"; | |
| export interface JoinRoomPayload { | |
| roomId?: string; | |
| username?: string; | |
| } | |
| export const JoinRoomSchema = z.object({ | |
| roomId: z.string().optional(), | |
| username: z.string().optional(), | |
| }); | |
| export function JoinRoomHandler(ctx: Context<JoinRoomPayload>) { | |
| // Set username if payload has it | |
| if (ctx.payload.username) { | |
| ctx.user.username = ctx.payload.username; | |
| } | |
| if (ctx.payload.roomId) ctx.payload.roomId = ctx.payload.roomId.toUpperCase(); | |
| let room: Room; | |
| if (ctx.payload.roomId && !ctx.server.rooms[ctx.payload.roomId]) { | |
| // User sent roomId, but room doesn't exist | |
| return ctx.ws.send( | |
| JSON.stringify({ | |
| message: "join_room_response", | |
| status: "room doesn't exist", | |
| }) | |
| ); | |
| // Custom ID Code: | |
| // room = new Room(ctx.payload.roomId); | |
| // room.id = room.id.toUpperCase(); | |
| // ctx.server.rooms[room.id] = room; | |
| } else if (!ctx.payload.roomId) { | |
| // Didn't include RoomID, creating new one | |
| room = new Room(ctx.payload.roomId); | |
| room.id = room.id.toUpperCase(); | |
| ctx.payload.roomId = room.id; | |
| ctx.server.rooms[room.id] = room; | |
| } else { | |
| // RoomId included and room exists, joining... | |
| room = ctx.server.rooms[ctx.payload.roomId]; | |
| if (room.hasUser(ctx.user.id)) { | |
| return ctx.ws.send( | |
| JSON.stringify({ | |
| message: "join_room_response", | |
| status: "failed, you are already part of this room", | |
| }) | |
| ); | |
| } | |
| } | |
| ctx.user.currentRoom = room; | |
| // Broadcasts message to room | |
| room.addUser(ctx.user); | |
| } | |