Ktor Resources type-safe routing plugin to generate URLs and paths

Viewed 34

I have recently updated current Ktor version to 2.1.x and Locations plugin is now deprecated. I'm refactoring code to use Resources plugin for type-safe routing. The documentation is lacking how to generate paths from Resources objects. I'm trying to create a redirect address based on a Resource and achieve a functionality like in Locations plugin to build URLs

val path = application.locations.href(Listing(name = "movies", page = 10, count = 20))

Resource definition

@Serializable
@Resource("clients")
class Clients() {
    @Serializable
    @Resource("{clientID}")
    class ID(val parent: Clients, val clientID: Int) {}
}

Route definition

fun Route.clientRouting(dao: ClientDao) {
    route("") {
        get<Clients> {
            call.respondText("Hello Client!")
        }

        get<Clients.ID> { clientID ->
            call.respondRedirect(...) //Redirect to Clients route
        }
    }
}

So... Is there a standard way of generating paths and URLs from Resources?

1 Answers

You can call the href method on an Application instance to get a URL for a specified resource:

get<Clients.ID> { clientID ->
    call.respondRedirect(call.application.href(Clients()))
}
Related