fartstack/backend/routes/room/[roomCode]/ws.dart

35 lines
1.3 KiB
Dart

import 'package:backend/db/database.dart';
import 'package:backend/db/db_access.dart';
import 'package:backend/socket_manager.dart';
import 'package:dart_frog/dart_frog.dart';
import 'package:dart_frog_web_socket/dart_frog_web_socket.dart';
import 'package:logging/logging.dart';
Future<Response> onRequest(RequestContext context, String roomCode) async {
final logger = Logger('room/[$roomCode]/ws');
final handler = webSocketHandler(protocols: ['game.room.v1'], (channel, protocol) async {
try {
channel.sink.add('test');
logger.finest(protocol);
final room = await Db.getRoomByCode(roomCode);
if (room == null) {
logger.finer('Room not found, aborting...');
await channel.sink.close(4404, 'Room not found');
return;
}
final user = context.read<User>();
final status = await SocketManager().addConnection(channel, roomUuid: room.uuid, userUuid: user.uuid);
if (status == Status.failure) {
logger.finer('Failed to spawn room isolate, closing connection.');
await channel.sink.close(4404, 'Room not found');
return;
}
} catch (e) {
logger.severe('Unexpected error occurred getting websocket connection', e, StackTrace.current);
}
});
return handler(context);
}