hallvard
09/30/2019, 7:20 AMatsushi-koshikizawa
09/30/2019, 8:05 AM@Location
, not to use routing
to define URL path
• then you can find which function to be called by the request.
2. Define @Location
and route (get
, post
, ...) one-to-one.
3. Do not nest routing
• then you can refer request parameters in the same way
4. Split routing definition. (see snippet)
( https://tech.bizreach.co.jp/posts/324/ktor-routing/ )Pavel Lechev
09/30/2019, 8:39 AMUser
, Product
, ...
In each of those, you declare an extension function (e.g. fun Application.user()
, fun Application.product()
) which then uses the routing { ...}
DSL for defining the relevant endpoints. Each of these functions is then becoming a Ktor module which is easy to install with module { ... }
and test with withTestApplication({ ...})
.// file User.kt
object User {
fun Application.user() {
routing {
get("/profile") {
// get user
}
post("/profile") {
// create user
}
}
}
}
// file Product.kt
object Product {
fun Application.product() {
routing {
get("/product") {
// get product
}
post("/product") {
// create product
}
}
}
}
// file Application.kt
object Application {
@JvmStatic
fun main(args: Array<String>) {
val env = applicationEngineEnvironment {
module {
user()
product()
}
}
embeddedServer(Netty, env).start(true)
}
}
// inside the test file ... testing User endpoints only
@Test
fun `testCreateUser`() = withTestApplication({
user()
}) {
handleRequest(<http://HttpMethod.Post|HttpMethod.Post>, "/profile") {
// configure request
}.also {
// assert response ...
}
}
hallvard
09/30/2019, 11:10 AMcy
09/30/2019, 3:39 PMhallvard
09/30/2019, 4:12 PMnapperley
09/30/2019, 8:52 PMfun Application.main() {
// Install Ktor features here...
routing {
homeRoute()
setupOwnerRoutes()
setupSiteRoutes()
setupSensorDataRoutes()
}
}
internal fun Route.setupSensorDataRoutes(testMode: Boolean = false) = route("/sensorData") {
timestampCountRoute(testMode)
sensorDataSiteChannelRoute(testMode)
sensorDataTimestampRangeRoute(testMode)
}
private fun Route.timestampCountRoute(testMode: Boolean = false) = get("/timestampCount") {
val count = if (testMode) 0 else Database.timestampCount()
call.respond(mapOf("total" to count))
}
fun Application.testMain() {
// Install Ktor features here...
routing {
homeRoute()
setupOwnerRoutes(true)
setupSiteRoutes(true)
setupSensorDataRoutes(true)
}
}