https://kotlinlang.org logo
#ktor
Title
# ktor
p

Philip Dukhov

11/12/2021, 5:15 AM
I'm writing a KMM app and I'd like to share Ktor routes between server and client. Right now I'm using string for route names:
Copy code
// server
route("user") {
    post("setFavorite") {
        
    }
}
route("auth") {
    post("facebook") {
        
    }
}
route("other") {

}
// client
<http://client.post|client.post><Unit>("/user/setFavorite")
I'd like to share this names to prevent errors. For example with interface like this:
Copy code
sealed interface ServerRoutes {
    sealed interface User: ServerRoutes {
        object SetFavorite: User
    }
    sealed interface Auth: ServerRoutes {
        object Facebook: Auth
    }
    object Other: ServerRoutes
}
Which could be used like this:
Copy code
// server
route(ServerRoutes.User) {
    post(ServerRoutes.User.SetFavorite) {
        
    }
}
route(ServerRoutes.Auth) {
    post(ServerRoutes.Auth.Facebook) {
        
    }
}
route(ServerRoutes.Other) {

}
// client
<http://client.post|client.post><Unit>(ServerRoutes.User.SetFavorite)
I think I can generate routes from class names using annotation processor, but I'm wondering if there's some existing solution?
h

hfhbd

11/12/2021, 11:19 AM
In theory: https://youtrack.jetbrains.com/issue/KTOR-1706 But until its implementation I simple define the routes in a shared API class, which takes an
HTTPClient
as parameter and use this API class in the clients and in the backend tests as well to prevent wrong names, different methods, response codes, body serialization etc: https://github.com/hfhbd/ComposeTodo/blob/main/shared/src/commonMain/kotlin/app/softwork/composetodo/API.kt https://github.com/hfhbd/ComposeTodo/blob/main/backend/src/test/kotlin/app/softwork/composetodo/TodoModuleKtTest.kt
p

Philip Dukhov

11/12/2021, 5:38 PM
@hfhbd Yes,
Locations
is exactly what I'm looking for! Sadly it doesn't support multiplatform so far, I only have found this feature request
a

Aleksei Tirman [JB]

11/15/2021, 9:01 AM
There is a work in progress for the implementation of the
Locations
plugin that will support multiplatform.
3 Views