Skip to content

Commit

Permalink
Implement getAllRoutes method (#3287)
Browse files Browse the repository at this point in the history
  • Loading branch information
marychatte committed Dec 6, 2022
1 parent dab18c0 commit eb86355
Show file tree
Hide file tree
Showing 3 changed files with 73 additions and 0 deletions.
4 changes: 4 additions & 0 deletions ktor-server/ktor-server-core/api/ktor-server-core.api
Expand Up @@ -1056,6 +1056,10 @@ public class io/ktor/server/routing/Route : io/ktor/server/application/Applicati
public fun toString ()Ljava/lang/String;
}

public final class io/ktor/server/routing/RouteKt {
public static final fun getAllRoutes (Lio/ktor/server/routing/Route;)Ljava/util/List;
}

public abstract class io/ktor/server/routing/RouteSelector {
public fun <init> ()V
public fun <init> (D)V
Expand Down
Expand Up @@ -133,3 +133,19 @@ public open class Route(
}
}
}

/**
* Return list of endpoints with handlers under this route.
*/
public fun Route.getAllRoutes(): List<Route> {
val endpoints = mutableListOf<Route>()
getAllRoutes(endpoints)
return endpoints
}

private fun Route.getAllRoutes(endpoints: MutableList<Route>) {
if (handlers.isNotEmpty()) {
endpoints.add(this)
}
children.forEach { it.getAllRoutes(endpoints) }
}
Expand Up @@ -4,7 +4,11 @@

package io.ktor.tests.routing

import io.ktor.http.*
import io.ktor.server.application.*
import io.ktor.server.response.*
import io.ktor.server.routing.*
import io.ktor.server.testing.*
import kotlin.test.*

class RouteTest {
Expand Down Expand Up @@ -37,4 +41,53 @@ class RouteTest {
assertTrue(root.developmentMode)
assertTrue(simpleChild.developmentMode)
}

@Test
fun testGetAllRoutes() = testApplication {
application {
val root = routing {
route("/shop") {
route("/customer") {
get("/{id}") {
call.respondText("OK")
}
post("/new") { }
}

route("/order") {
route("/shipment") {
get { }
post {
call.respondText("OK")
}
put {
call.respondText("OK")
}
}
}
}

route("/info", HttpMethod.Get) {
post("new") {}

handle {
call.respondText("OK")
}
}
}

val endpoints = root.getAllRoutes()
assertTrue { endpoints.size == 7 }
val expected = setOf(
"/shop/customer/{id}/(method:GET)",
"/shop/customer/new/(method:POST)",
"/shop/order/shipment/(method:GET)",
"/shop/order/shipment/(method:PUT)",
"/shop/order/shipment/(method:POST)",
"/info/(method:GET)",
"/info/(method:GET)/new/(method:POST)"
)
assertEquals(expected, endpoints.map { it.toString() }.toSet())
}
}
}

0 comments on commit eb86355

Please sign in to comment.