Skip to content

Commit 6c910ad

Browse files
committed
#1457 - Add RepresentationModel.mapLink(LinkRelation, Function<Link, Link>).
1 parent 0aae59a commit 6c910ad

File tree

2 files changed

+30
-0
lines changed

2 files changed

+30
-0
lines changed

src/main/java/org/springframework/hateoas/RepresentationModel.java

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@
2121
import java.util.Collections;
2222
import java.util.List;
2323
import java.util.Optional;
24+
import java.util.function.Function;
2425
import java.util.function.Supplier;
2526
import java.util.stream.Collectors;
2627

@@ -299,6 +300,25 @@ public List<Link> getLinks(LinkRelation relation) {
299300
return getLinks(relation.value());
300301
}
301302

303+
/**
304+
* Replaces the link(s) with the given {@link LinkRelation} with the mapper applied to each of the links.
305+
*
306+
* @param relation the {@link LinkRelation} to select the source link(s), must not be {@literal null}.
307+
* @param mapper the {@link Function} to apply to the current link, must not be {@literal null}.
308+
* @return will never be {@literal null}.
309+
* @since 1.3
310+
*/
311+
public T mapLink(LinkRelation relation, Function<Link, Link> mapper) {
312+
313+
getLinks(relation).forEach(it -> {
314+
315+
links.remove(it);
316+
links.add(mapper.apply(it));
317+
});
318+
319+
return (T) this;
320+
}
321+
302322
/*
303323
* (non-Javadoc)
304324
* @see java.lang.Object#toString()

src/test/java/org/springframework/hateoas/RepresentationModelUnitTest.java

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -194,4 +194,14 @@ void addsGuardedLinks() {
194194
model.addAllIf(false, () -> Links.of(Link.of("not-added", "bar")));
195195
assertThat(model.hasLink("bar")).isFalse();
196196
}
197+
198+
@Test // #1457
199+
void replacesLink() {
200+
201+
RepresentationModel<?> model = new RepresentationModel<>();
202+
model.add(Link.of("/foo", IanaLinkRelations.SELF));
203+
model.mapLink(IanaLinkRelations.SELF, it -> Link.of("/bar"));
204+
205+
assertThat(model.getRequiredLink(IanaLinkRelations.SELF).getHref()).isEqualTo("/bar");
206+
}
197207
}

0 commit comments

Comments
 (0)