#1457 - Add RepresentationModel.mapLink(LinkRelation, Function<Link, Link>).

This commit is contained in:
Oliver Drotbohm
2021-02-11 19:00:26 +01:00
parent 0aae59a5e3
commit 6c910adf16
2 changed files with 30 additions and 0 deletions

View File

@@ -21,6 +21,7 @@ import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import java.util.function.Function;
import java.util.function.Supplier;
import java.util.stream.Collectors;
@@ -299,6 +300,25 @@ public class RepresentationModel<T extends RepresentationModel<? extends T>> {
return getLinks(relation.value());
}
/**
* Replaces the link(s) with the given {@link LinkRelation} with the mapper applied to each of the links.
*
* @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
*/
public T mapLink(LinkRelation relation, Function<Link, Link> mapper) {
getLinks(relation).forEach(it -> {
links.remove(it);
links.add(mapper.apply(it));
});
return (T) this;
}
/*
* (non-Javadoc)
* @see java.lang.Object#toString()

View File

@@ -194,4 +194,14 @@ class RepresentationModelUnitTest {
model.addAllIf(false, () -> Links.of(Link.of("not-added", "bar")));
assertThat(model.hasLink("bar")).isFalse();
}
@Test // #1457
void replacesLink() {
RepresentationModel<?> model = new RepresentationModel<>();
model.add(Link.of("/foo", IanaLinkRelations.SELF));
model.mapLink(IanaLinkRelations.SELF, it -> Link.of("/bar"));
assertThat(model.getRequiredLink(IanaLinkRelations.SELF).getHref()).isEqualTo("/bar");
}
}