Skip to content

Commit

Permalink
fix: type-safe routing limitation
Browse files Browse the repository at this point in the history
There was a limitation routing from parent to child route using type-safe types.
  • Loading branch information
programadorthi committed Aug 13, 2024
1 parent 8317ab5 commit 9f00520
Show file tree
Hide file tree
Showing 3 changed files with 59 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -85,8 +85,13 @@ public fun <T : Any> Route.resource(
val path = resources.resourcesFormat.encodeToPathPattern(serializer)
val queryParameters = resources.resourcesFormat.encodeToQueryParameters(serializer)
var route = this
var routePath = route.toString()
if (routePath.startsWith("/")) {
routePath = routePath.removePrefix("/")
}
val finalPath = path.removePrefix(routePath)
// Required for register to parents
route(path = path, name = null) {
route(path = finalPath, name = null) {
route =
queryParameters.fold(this) { entry, query ->
val selector =
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import dev.programadorthi.routing.core.call
import dev.programadorthi.routing.core.errors.RouteNotFoundException
import dev.programadorthi.routing.core.install
import dev.programadorthi.routing.core.routing
import dev.programadorthi.routing.resources.helper.ParentRouting
import dev.programadorthi.routing.resources.helper.Path
import io.ktor.http.Parameters
import io.ktor.http.parametersOf
Expand Down Expand Up @@ -469,4 +470,47 @@ class ResourcesTest {
assertEquals(parametersOf(), result?.parameters)
assertEquals("body content", body, "should have received a body")
}

@Test
fun shouldDoParentToChildRoutingUsingChildType() =
runTest {
// GIVEN
val job = Job()
var result: ApplicationCall? = null

val parent =
routing(
rootPath = "/parent",
parentCoroutineContext = coroutineContext + job,
) {
install(Resources)

handle<Path.Id> {
}
}

routing(
rootPath = "/child",
parentCoroutineContext = coroutineContext + job,
parent = parent,
) {
install(Resources)

handle<ParentRouting.ChildRouting.Destination> {
result = call
job.complete()
}
}

// WHEN
parent.call(resource = ParentRouting.ChildRouting.Destination())
advanceTimeBy(99)

// THEN
assertNotNull(result)
assertEquals("/parent/child/destination", "${result?.uri}")
assertEquals("", "${result?.name}")
assertEquals(RouteMethod.Empty, result?.routeMethod)
assertEquals(Parameters.Empty, result?.parameters)
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -7,3 +7,12 @@ class Path {
@Resource("{id}")
class Id(val parent: Path = Path(), val id: Int)
}

@Resource("/parent")
class ParentRouting {
@Resource("/child")
class ChildRouting(val parent: ParentRouting = ParentRouting()) {
@Resource("/destination")
class Destination(val parent: ChildRouting = ChildRouting())
}
}

0 comments on commit 9f00520

Please sign in to comment.