Skip to content

Commit

Permalink
Try JSON serialization with a const kotlinx.serialization serializer …
Browse files Browse the repository at this point in the history
…in `vertx-web-kotlinx`
  • Loading branch information
ShreckYe committed Jan 26, 2024
1 parent ddbc80b commit 678f67b
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -15,10 +15,12 @@ import io.vertx.sqlclient.PreparedQuery
import io.vertx.sqlclient.Row
import io.vertx.sqlclient.RowSet
import io.vertx.sqlclient.Tuple
import kotlinx.coroutines.*
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.html.*
import kotlinx.html.stream.appendHTML
import kotlinx.serialization.Serializable
import kotlinx.serialization.SerializationStrategy
import kotlinx.serialization.encodeToString
import kotlinx.serialization.json.Json
import java.net.SocketException
Expand Down Expand Up @@ -118,6 +120,17 @@ class MainVerticle(val hasDb: Boolean) : CoroutineVerticle() {
}
}

// copied and adapted from above
inline fun <T : Any> Route.jsonResponseHandlerWithSerializer(
serializer: SerializationStrategy<T>, crossinline requestHandler: suspend (RoutingContext) -> @Serializable T
) =
checkedCoroutineHandlerUnconfined {
it.response().run {
putJsonResponseHeader()
end(Json.encodeToString(serializer, requestHandler(it)))/*.await()*/
}
}

suspend fun selectRandomWorlds(queries: Int): List<World> {
val rowSets = List(queries) {
selectWorldQuery.execute(Tuple.of(randomIntBetween1And10000()))
Expand All @@ -126,7 +139,7 @@ class MainVerticle(val hasDb: Boolean) : CoroutineVerticle() {
}

fun Router.routes() {
get("/json").jsonResponseHandler {
get("/json").jsonResponseHandlerWithSerializer(messageSerializer) {
jsonSerializationMessage
}

Expand Down
2 changes: 2 additions & 0 deletions frameworks/Kotlin/vertx-web-kotlinx/src/main/kotlin/Models.kt
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
import kotlinx.serialization.Serializable
import kotlinx.serialization.serializer
import kotlin.random.Random

@Serializable
class Message(val message: String)

val jsonSerializationMessage = Message("Hello, World!")
val messageSerializer = serializer<Message>()

@Serializable
data class World(val id: Int, val randomNumber: Int)
Expand Down

0 comments on commit 678f67b

Please sign in to comment.