create a websocket route to create and join a game
This commit is contained in:
@@ -5,17 +5,15 @@ import eventDemo.business.entity.GameId
|
||||
import eventDemo.business.entity.Player
|
||||
import eventDemo.business.event.eventListener.PlayerNotificationEventListener
|
||||
import eventDemo.business.notification.Notification
|
||||
import eventDemo.configuration.ktor.BadRequestException
|
||||
import eventDemo.configuration.ktor.HttpErrorBadRequest
|
||||
import eventDemo.libs.fromFrameChannel
|
||||
import eventDemo.libs.toObjectChannel
|
||||
import io.github.oshai.kotlinlogging.withLoggingContext
|
||||
import io.ktor.http.parameters
|
||||
import io.ktor.server.application.ApplicationCall
|
||||
import io.ktor.server.auth.authenticate
|
||||
import io.ktor.server.auth.jwt.JWTPrincipal
|
||||
import io.ktor.server.auth.principal
|
||||
import io.ktor.server.routing.Route
|
||||
import io.ktor.server.websocket.DefaultWebSocketServerSession
|
||||
import io.ktor.server.websocket.webSocket
|
||||
import kotlinx.coroutines.DelicateCoroutinesApi
|
||||
import kotlinx.coroutines.GlobalScope
|
||||
@@ -30,13 +28,27 @@ fun Route.gameWebSocket(
|
||||
commandHandler: GameCommandHandler,
|
||||
) {
|
||||
authenticate {
|
||||
webSocket("/game/{id}") {
|
||||
webSocket("/games/new") {
|
||||
runWebSocket(GameId(), commandHandler, playerNotificationListener)
|
||||
}
|
||||
|
||||
webSocket("/games/{id}") {
|
||||
val gameId = GameId(UUID.fromString(call.parameters["id"]!!))
|
||||
runWebSocket(gameId, commandHandler, playerNotificationListener)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@DelicateCoroutinesApi
|
||||
private fun DefaultWebSocketServerSession.runWebSocket(
|
||||
gameId: GameId,
|
||||
commandHandler: GameCommandHandler,
|
||||
playerNotificationListener: PlayerNotificationEventListener,
|
||||
) {
|
||||
val currentPlayer = call.getPlayer()
|
||||
val gameId =
|
||||
call.parameters["id"]?.let { GameId(UUID.fromString(it)) }
|
||||
?: throw BadRequestException(HttpErrorBadRequest("No ID fore the game"))
|
||||
val outgoingFrameChannel: SendChannel<Notification> = fromFrameChannel(outgoing)
|
||||
withLoggingContext("currentPlayer" to currentPlayer.toString()) {
|
||||
// TODO change GlobalScope
|
||||
GlobalScope.launch {
|
||||
commandHandler.handle(
|
||||
currentPlayer,
|
||||
@@ -53,8 +65,6 @@ fun Route.gameWebSocket(
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun ApplicationCall.getPlayer() =
|
||||
principal<JWTPrincipal>()!!.run {
|
||||
|
||||
Reference in New Issue
Block a user