diff --git a/src/main/java/org/springframework/hateoas/RepresentationModel.java b/src/main/java/org/springframework/hateoas/RepresentationModel.java index e7437980..53bd198f 100755 --- a/src/main/java/org/springframework/hateoas/RepresentationModel.java +++ b/src/main/java/org/springframework/hateoas/RepresentationModel.java @@ -309,6 +309,25 @@ public class RepresentationModel> { * @since 1.3 */ public T mapLink(LinkRelation relation, Function 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 mapper) { + + if (!condition) { + return (T) this; + } getLinks(relation).forEach(it -> { diff --git a/src/test/java/org/springframework/hateoas/RepresentationModelUnitTest.java b/src/test/java/org/springframework/hateoas/RepresentationModelUnitTest.java index d190b79c..7f619622 100755 --- a/src/test/java/org/springframework/hateoas/RepresentationModelUnitTest.java +++ b/src/test/java/org/springframework/hateoas/RepresentationModelUnitTest.java @@ -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"); + } }