Add leave table server API

This commit is contained in:
Christoph Hagen 2021-11-30 11:56:51 +01:00
parent f81b8e4119
commit 775ac91cc8
3 changed files with 39 additions and 8 deletions

View File

@ -90,7 +90,18 @@ final class Database {
tables.getPublicTableInfos()
}
func join(tableId: TableId, player: PlayerName) -> TableManagement.JoinTableResult {
tables.join(tableId: tableId, player: player)
func join(tableId: TableId, playerToken: SessionToken) -> JoinTableResult {
guard let player = players.registeredPlayerExists(withSessionToken: playerToken) else {
return .invalidToken
}
return tables.join(tableId: tableId, player: player)
}
func leaveTable(playerToken: SessionToken) -> Bool {
guard let player = players.registeredPlayerExists(withSessionToken: playerToken) else {
return false
}
tables.remove(player: player)
return true
}
}

View File

@ -79,8 +79,6 @@ final class TableManagement {
players.append(player)
if let oldTable = playerTables[tableId] {
remove(player: player, fromTable: oldTable)
// TODO: End game if needed
//
}
tablePlayers[tableId] = players
playerTables[tableId] = tableId
@ -89,10 +87,15 @@ final class TableManagement {
func remove(player: PlayerName, fromTable tableId: TableId) {
tablePlayers[tableId] = tablePlayers[tableId]?.filter { $0 != player }
// TODO: End connection for removed user
// TODO: End game if needed, send info to remaining players
}
func remove(player: PlayerName) {
fatalError()
guard let tableId = playerTables[player] else {
return
}
remove(player: player, fromTable: tableId)
}
func connect(player: PlayerName, using socket: WebSocket) -> Bool {

View File

@ -235,10 +235,9 @@ func routes(_ app: Application) throws {
let token = req.body.string else {
throw Abort(.badRequest)
}
guard let player = database.registeredPlayerExists(withSessionToken: token) else {
switch database.join(tableId: table, playerToken: token) {
case .invalidToken:
throw Abort(.unauthorized) // 401
}
switch database.join(tableId: table, player: player) {
case .tableNotFound:
throw Abort(.gone) // 410
case .tableIsFull:
@ -247,4 +246,22 @@ func routes(_ app: Application) throws {
return ""
}
}
/**
Leave the current table.
- Parameter token: The session token of the player, as a string in the request body
- Throws:
- 400: Missing token
- 401: The session token is invalid
- Returns: Nothing
*/
app.post("table", "leave") { req -> String in
guard let token = req.body.string else {
throw Abort(.badRequest)
}
guard database.leaveTable(playerToken: token) else {
throw Abort(.unauthorized) // 401
}
return ""
}
}