Skip to content

Commit 759785f

Browse files
committed
#1504 - Add RepresentationModel.mapLinkIf(…).
1 parent 5ec99df commit 759785f

File tree

2 files changed

+34
-0
lines changed

2 files changed

+34
-0
lines changed

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

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -309,6 +309,25 @@ public List<Link> getLinks(LinkRelation relation) {
309309
* @since 1.3
310310
*/
311311
public T mapLink(LinkRelation relation, Function<Link, Link> mapper) {
312+
return mapLinkIf(true, relation, mapper);
313+
}
314+
315+
/**
316+
* Replaces the link(s) with the given {@link LinkRelation} with the mapper applied to each of the links if the given
317+
* condition is true.
318+
*
319+
* @param condition the condition that needs to be {@literal true} to apply the mapping.
320+
* @param relation the {@link LinkRelation} to select the source link(s), must not be {@literal null}.
321+
* @param mapper the {@link Function} to apply to the current link, must not be {@literal null}.
322+
* @return will never be {@literal null}.
323+
* @since 1.3
324+
*/
325+
@SuppressWarnings("unchecked")
326+
public T mapLinkIf(boolean condition, LinkRelation relation, Function<Link, Link> mapper) {
327+
328+
if (!condition) {
329+
return (T) this;
330+
}
312331

313332
getLinks(relation).forEach(it -> {
314333

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

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -204,4 +204,19 @@ void replacesLink() {
204204

205205
assertThat(model.getRequiredLink(IanaLinkRelations.SELF).getHref()).isEqualTo("/bar");
206206
}
207+
208+
@Test // #1504
209+
void mapsLinkConditionally() {
210+
211+
RepresentationModel<?> model = new RepresentationModel<>();
212+
model.add(Link.of("/foo", IanaLinkRelations.SELF));
213+
214+
model.mapLinkIf(false, IanaLinkRelations.SELF, it -> Link.of("/bar"));
215+
216+
assertThat(model.getRequiredLink(IanaLinkRelations.SELF).getHref()).isEqualTo("/foo");
217+
218+
model.mapLinkIf(true, IanaLinkRelations.SELF, it -> Link.of("/bar"));
219+
220+
assertThat(model.getRequiredLink(IanaLinkRelations.SELF).getHref()).isEqualTo("/bar");
221+
}
207222
}

0 commit comments

Comments
 (0)