Created
November 14, 2018 11:44
-
-
Save bob983/b26f7af740c6aa0c4913aec43b209c06 to your computer and use it in GitHub Desktop.
POJO request params workaround
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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)) | |
... | |
} | |
} | |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 } } | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//the marker interface - it was added for different reason, but works well for the workaround as well :) | |
interface QueryParam | |
//query params POJO | |
data class ListConversationParams( | |
val tag: String?, | |
@get:PositiveNumber | |
val assigned_to: String?, | |
@get:ValidCommaSeparatedList | |
val mailbox: String? | |
) : QueryParam |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment