Skip to content

Instantly share code, notes, and snippets.

@bob983
Created November 14, 2018 11:44
Show Gist options
  • Save bob983/b26f7af740c6aa0c4913aec43b209c06 to your computer and use it in GitHub Desktop.
Save bob983/b26f7af740c6aa0c4913aec43b209c06 to your computer and use it in GitHub Desktop.
POJO request params workaround
class Controller {
@GetMapping
fun list(
@AuthenticationPrincipal authorizedUser: AuthorizedUser,
uriBuilder: UriComponentsBuilder,
@Validated params: ListConversationParams): Single<PaginatedResources<..>> {
val selfLink = selfLink(uriBuilder, on(javaClass).list(authorizedUser, uriBuilder, prams))
...
}
}
object HateoasHelper {
fun link(builder: UriComponentsBuilder, invocationInfo: Any): Link {
val queryParams = getQueryParams(invocationInfo)
val uri = MvcUriComponentsBuilder
.relativeTo(builder)
.withMethodCall(invocationInfo)
.queryParams(queryParams)
.build()
return Link(uri)
}
/**
* Extracts query params suitable for `MvcUriComponentsBuilder`:
*
* It looks for method argument of type `QueryParams` which it inspects
* and reads all public members and their values
*/
private fun getQueryParams(invocationInfo: Any): MultiValueMap<String, String> {
val arguments = when (invocationInfo) {
is MethodInvocationInfo -> invocationInfo.argumentValues
else -> emptyArray()
}
val ordinaryMap = arguments
.mapNotNull { it as? QueryParams }
.flatMap { getValues(it) }
.toMap()
.mapValues { listOf(it.value.toString()) }
return LinkedMultiValueMap(ordinaryMap)
}
private fun getValues(params: QueryParams): List<Pair<String, Any>> = params
.javaClass
.kotlin
.declaredMemberProperties
.filter { it.visibility == KVisibility.PUBLIC }
.map { it.name to it.get(params) }
.mapNotNull { pair -> pair.second?.let { pair.first to it } }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment