Fix ws.ts: use SocketStream from @fastify/websocket v8
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
@@ -1,36 +1,37 @@
|
|||||||
import { FastifyPluginAsync } from 'fastify'
|
import { FastifyPluginAsync } from 'fastify'
|
||||||
import fastifyWebsocket from '@fastify/websocket'
|
import fastifyWebsocket from '@fastify/websocket'
|
||||||
import type { WebSocket, RawData } from 'ws'
|
import type { SocketStream } from '@fastify/websocket'
|
||||||
|
import type { RawData } from 'ws'
|
||||||
|
|
||||||
// hotel slug → set of connected clients
|
// hotel slug → set of connected streams
|
||||||
const hotelRooms = new Map<string, Set<WebSocket>>()
|
const hotelRooms = new Map<string, Set<SocketStream>>()
|
||||||
|
|
||||||
const ws: FastifyPluginAsync = async (fastify) => {
|
const ws: FastifyPluginAsync = async (fastify) => {
|
||||||
await fastify.register(fastifyWebsocket)
|
await fastify.register(fastifyWebsocket)
|
||||||
|
|
||||||
fastify.get<{ Querystring: { hotel?: string; token?: string } }>(
|
fastify.get<{ Querystring: { hotel?: string } }>(
|
||||||
'/ws',
|
'/ws',
|
||||||
{ websocket: true },
|
{ websocket: true },
|
||||||
(socket, request) => {
|
(connection: SocketStream, request) => {
|
||||||
const hotel = request.query.hotel ?? ''
|
const hotel = (request.query as { hotel?: string }).hotel ?? ''
|
||||||
if (!hotel) { socket.close(4001, 'hotel required'); return }
|
if (!hotel) { connection.socket.close(4001, 'hotel required'); return }
|
||||||
|
|
||||||
if (!hotelRooms.has(hotel)) hotelRooms.set(hotel, new Set())
|
if (!hotelRooms.has(hotel)) hotelRooms.set(hotel, new Set())
|
||||||
hotelRooms.get(hotel)!.add(socket)
|
hotelRooms.get(hotel)!.add(connection)
|
||||||
|
|
||||||
socket.on('message', (raw: RawData) => {
|
connection.socket.on('message', (raw: RawData) => {
|
||||||
const data = raw.toString()
|
const data = raw.toString()
|
||||||
const peers = hotelRooms.get(hotel)
|
const peers = hotelRooms.get(hotel)
|
||||||
if (!peers) return
|
if (!peers) return
|
||||||
peers.forEach(client => {
|
peers.forEach(peer => {
|
||||||
if (client !== socket && client.readyState === 1) {
|
if (peer !== connection && peer.socket.readyState === 1) {
|
||||||
client.send(data)
|
peer.socket.send(data)
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|
||||||
socket.on('close', () => {
|
connection.socket.on('close', () => {
|
||||||
hotelRooms.get(hotel)?.delete(socket)
|
hotelRooms.get(hotel)?.delete(connection)
|
||||||
if (hotelRooms.get(hotel)?.size === 0) hotelRooms.delete(hotel)
|
if (hotelRooms.get(hotel)?.size === 0) hotelRooms.delete(hotel)
|
||||||
})
|
})
|
||||||
},
|
},
|
||||||
|
|||||||
Reference in New Issue
Block a user