#1504 - Add RepresentationModel.mapLinkIf(…).

This commit is contained in:
Oliver Drotbohm
2021-03-25 17:38:07 +01:00
parent 5ec99df255
commit 759785f98e
2 changed files with 34 additions and 0 deletions

View File

@@ -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 -> {

View File

@@ -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");
}
}