Player manager in progress

This commit is contained in:
Claude Brisson
2023-05-14 13:20:25 +02:00
parent 06a4ce4f4c
commit fd67d4e044
3 changed files with 48 additions and 0 deletions

View File

@@ -1,4 +1,23 @@
package org.jeudego.pairgoth.api
import com.republicate.kson.Json
import org.jeudego.pairgoth.model.Player
import org.jeudego.pairgoth.model.Tournament
import org.jeudego.pairgoth.model.fromJson
import org.jeudego.pairgoth.store.Store
import javax.servlet.http.HttpServletRequest
class PlayerHandler: ApiHandler {
override fun post(request: HttpServletRequest): Json {
val json = getPayload(request)
if (!json.isObject) ApiHandler.badRequest("expecting a json object")
val payload = json.asObject()
// player parsing
val player = Player.fromJson(payload)
Store.addPlayer(player)
return Json.Object("success" to true, "id" to player.id)
}
}

View File

@@ -1,5 +1,9 @@
package org.jeudego.pairgoth.model
import com.republicate.kson.Json
import org.jeudego.pairgoth.api.ApiHandler.Companion.badRequest
import org.jeudego.pairgoth.store.Store
class Player(
id: Int,
name: String,
@@ -13,3 +17,23 @@ class Player(
// used to store external IDs ("FFG" => FFG ID, "EGF" => EGF PIN, "AGA" => AGA ID ...)
val externalIds = mutableMapOf<String, String>()
}
fun Player.Companion.fromJson(json: Json.Object) = Player(
id = json.getInt("id") ?: Store.nextPlayerId,
name = json.getString("name") ?: badRequest("missing name"),
firstname = json.getString("firstname") ?: badRequest("missing firstname"),
rating = json.getDouble("rating") ?: badRequest("missing rating"),
rank = json.getInt("rank") ?: badRequest("missing rank"),
country = json.getString("country") ?: badRequest("missing country"),
club = json.getString("club") ?: ""
)
fun Player.toJson() = Json.Object(
"id" to id,
"name" to name,
"firstname" to firstname,
"rating" to rating,
"rank" to rank,
"country" to country,
"club" to club
)

View File

@@ -3,6 +3,7 @@ package org.jeudego.pairgoth.store
import org.jeudego.pairgoth.model.Player
import org.jeudego.pairgoth.model.Tournament
import java.util.concurrent.atomic.AtomicInteger
import kotlin.math.E
object Store {
private val _nextTournamentId = AtomicInteger()
@@ -21,4 +22,8 @@ object Store {
fun getTournament(id: Int) = tournaments[id]
fun getTournamentsIDs(): Set<Int> = tournaments.keys
fun addPlayer(player: Player) {
if (players.containsKey(player.id)) throw Error("player id #${player.id} already exists")
players[player.id] = player
}
}