Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

KTOR-581 Implement getAllRoutes method #3287

Merged
merged 1 commit into from Dec 6, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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())
}
}
}