fartstack/backend/routes/create_room.dart

54 lines
1.5 KiB
Dart

import 'dart:io';
import 'dart:math';
import 'package:backend/service/db_access.dart';
import 'package:dart_frog/dart_frog.dart';
import 'package:logging/logging.dart';
import 'package:shared_models/room.dart';
final log = Logger('create_room/');
Future<Response> onRequest(RequestContext context) async {
// Only allow POST requests
if (context.request.method != HttpMethod.post) {
return Response(statusCode: HttpStatus.methodNotAllowed);
}
try {
// Generate a random 6-letter room code
const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
final random = Random();
final roomCode = String.fromCharCodes(
Iterable.generate(
6,
(_) => chars.codeUnitAt(random.nextInt(chars.length)),
),
);
// Create the room
final room = await Db.createRoom(roomCode: roomCode);
if (room == null) {
return Response.json(
statusCode: HttpStatus.internalServerError,
body: CreateRoomResponse(
error: 'Unexpected error: unable to create room',
success: false,
roomCode: null,
).toJson(),
);
}
// Return the room code
return Response.json(
body: CreateRoomResponse(success: true, roomCode: room.code).toJson(),
);
} catch (e) {
log.severe('Error:', e);
return Response.json(
statusCode: HttpStatus.internalServerError,
body: CreateRoomResponse(success: false, roomCode: null, error: 'Internal server error').toJson(),
);
}
}