#1504 - Add RepresentationModel.mapLinkIf(…).
This commit is contained in:
@@ -309,6 +309,25 @@ public class RepresentationModel<T extends RepresentationModel<? extends T>> {
|
||||
* @since 1.3
|
||||
*/
|
||||
public T mapLink(LinkRelation relation, Function<Link, Link> mapper) {
|
||||
return mapLinkIf(true, relation, mapper);
|
||||
}
|
||||
|
||||
/**
|
||||
* Replaces the link(s) with the given {@link LinkRelation} with the mapper applied to each of the links if the given
|
||||
* condition is true.
|
||||
*
|
||||
* @param condition the condition that needs to be {@literal true} to apply the mapping.
|
||||
* @param relation the {@link LinkRelation} to select the source link(s), must not be {@literal null}.
|
||||
* @param mapper the {@link Function} to apply to the current link, must not be {@literal null}.
|
||||
* @return will never be {@literal null}.
|
||||
* @since 1.3
|
||||
*/
|
||||
@SuppressWarnings("unchecked")
|
||||
public T mapLinkIf(boolean condition, LinkRelation relation, Function<Link, Link> mapper) {
|
||||
|
||||
if (!condition) {
|
||||
return (T) this;
|
||||
}
|
||||
|
||||
getLinks(relation).forEach(it -> {
|
||||
|
||||
|
||||
@@ -204,4 +204,19 @@ class RepresentationModelUnitTest {
|
||||
|
||||
assertThat(model.getRequiredLink(IanaLinkRelations.SELF).getHref()).isEqualTo("/bar");
|
||||
}
|
||||
|
||||
@Test // #1504
|
||||
void mapsLinkConditionally() {
|
||||
|
||||
RepresentationModel<?> model = new RepresentationModel<>();
|
||||
model.add(Link.of("/foo", IanaLinkRelations.SELF));
|
||||
|
||||
model.mapLinkIf(false, IanaLinkRelations.SELF, it -> Link.of("/bar"));
|
||||
|
||||
assertThat(model.getRequiredLink(IanaLinkRelations.SELF).getHref()).isEqualTo("/foo");
|
||||
|
||||
model.mapLinkIf(true, IanaLinkRelations.SELF, it -> Link.of("/bar"));
|
||||
|
||||
assertThat(model.getRequiredLink(IanaLinkRelations.SELF).getHref()).isEqualTo("/bar");
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user