How to use Spring HATEOAS "linkTo" with Kotlin DSL?

Viewed 869

There is a Kotlin variant of the linkTo method of Spring HATEOAS that takes a reified type parameter for the Controller and function for the body:

org.springframework.hateoas.server.mvc WebMvcLinkBuilderDslKt.class public inline fun <reified C> linkTo(
    func: C.() → Unit
): WebMvcLinkBuilder

but I have no idea how to actually use it, since I haven't found any useful documentation and the API is not really intuitive. I tried it like this:

linkTo<MyHandler> { findById(req) }.toUriComponentsBuilder().build(mapOf("id" to 1)).toURL()

I think it is wrong to use the req object of the surrounding method, if the link should point to another method. The result is simply http://localhost:8080 without any path or parameter.

How can I build a link with the Kotlin DSL?

Since I'm using Spring WebMvc.fn: Is there another way to build links with this framework?

2 Answers

The func parameter of the linkTo function is a function with receiver, where the receiver must be a Spring controller. Inside the function you should invoke one of the controller's methods. When Spring HATEOAS calls the func, it passes as the receiver not the actual controller, but a proxy. Method invocation on the proxy is intercepted and a link is created based on the method call (including the method call arguments).

Given a controller:

@RestController
class TestController {

    @RequestMapping("/test/{path-var}")
    @ResponseBody
    fun test(@PathVariable("path-var") pathVar: String,
             @RequestParam("param") param: Int) = Response()
}

the following invocation would produce http://localhost:8080/test/any?param=123

linkTo<TestController> { test("any", 123) }

I hope it helps, for me work like this:

for (user in pageUserModel.toList()) {
            user.add(
                linkTo(
                    methodOn(UserController::class.javaObjectType)
                        .getOneUser(user.userId!!)
                ).withSelfRel()
            )
        }
Related