#1014 - Added API to conditionally add links to RepresentationModel.
This allows more fluent usage of the API.
This commit is contained in:
@@ -19,6 +19,7 @@ import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.function.Supplier;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import org.springframework.lang.Nullable;
|
||||
@@ -102,6 +103,41 @@ public class RepresentationModel<T extends RepresentationModel<? extends T>> {
|
||||
return (T) this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds the {@link Link} produced by the given Supplier if the guard is {@literal true}.
|
||||
*
|
||||
* @param guard whether to add the {@link Link} produced by the given {@link Supplier}.
|
||||
* @param link the {@link Link} to add in case the guard is {@literal true}.
|
||||
* @return
|
||||
*/
|
||||
@SuppressWarnings("unchecked")
|
||||
public T addIf(boolean guard, Supplier<Link> link) {
|
||||
|
||||
if (guard) {
|
||||
add(link.get());
|
||||
}
|
||||
|
||||
return (T) this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds all {@link Link}s produced by the given Supplier if the guard is {@literal true}.
|
||||
*
|
||||
* @param guard whether to add the {@link Link}s produced by the given {@link Supplier}.
|
||||
* @param links the {@link Link}s to add in case the guard is {@literal true}.
|
||||
* @return
|
||||
* @see Links
|
||||
*/
|
||||
@SuppressWarnings("unchecked")
|
||||
public T addAllIf(boolean guard, Supplier<? extends Iterable<Link>> links) {
|
||||
|
||||
if (guard) {
|
||||
add(links.get());
|
||||
}
|
||||
|
||||
return (T) this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns whether the resource contains {@link Link}s at all.
|
||||
*
|
||||
|
||||
@@ -170,4 +170,28 @@ class RepresentationModelUnitTest {
|
||||
assertThat(support.hasLink("self")).isTrue();
|
||||
assertThat(support.hasLink("another")).isTrue();
|
||||
}
|
||||
|
||||
@Test // #1014
|
||||
void addsGuardedLink() {
|
||||
|
||||
RepresentationModel<?> model = new RepresentationModel<>();
|
||||
|
||||
model.addIf(true, () -> new Link("added", "foo"));
|
||||
assertThat(model.hasLink("foo")).isTrue();
|
||||
|
||||
model.addIf(false, () -> new Link("not-added", "bar"));
|
||||
assertThat(model.hasLink("bar")).isFalse();
|
||||
}
|
||||
|
||||
@Test // #1014
|
||||
void addsGuardedLinks() {
|
||||
|
||||
RepresentationModel<?> model = new RepresentationModel<>();
|
||||
|
||||
model.addAllIf(true, () -> Links.of(new Link("added", "foo")));
|
||||
assertThat(model.hasLink("foo")).isTrue();
|
||||
|
||||
model.addAllIf(false, () -> Links.of(new Link("not-added", "bar")));
|
||||
assertThat(model.hasLink("bar")).isFalse();
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user