Skip to content

Commit

Permalink
#1457 - Add RepresentationModel.mapLink(LinkRelation, Function<Link, …
Browse files Browse the repository at this point in the history
…Link>).
  • Loading branch information
odrotbohm committed Feb 11, 2021
1 parent 0aae59a commit 6c910ad
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 0 deletions.
20 changes: 20 additions & 0 deletions src/main/java/org/springframework/hateoas/RepresentationModel.java
Expand Up @@ -21,6 +21,7 @@
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;

Expand Down Expand Up @@ -299,6 +300,25 @@ public List<Link> getLinks(LinkRelation relation) {
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()
Expand Down
Expand Up @@ -194,4 +194,14 @@ void addsGuardedLinks() {
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");
}
}

0 comments on commit 6c910ad

Please sign in to comment.