For manager-based employee aggregate, swap out default "self link.

Resolves: #29
This commit is contained in:
Greg Turnquist
2019-12-12 11:15:46 -06:00
parent cfbc9eacfb
commit 287995aa1a

View File

@@ -15,11 +15,16 @@
*/
package org.springframework.hateoas.examples;
import static org.springframework.hateoas.server.mvc.WebMvcLinkBuilder.*;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.StreamSupport;
import org.springframework.hateoas.CollectionModel;
import org.springframework.hateoas.EntityModel;
import org.springframework.hateoas.IanaLinkRelations;
import org.springframework.hateoas.Link;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
@@ -80,7 +85,21 @@ class EmployeeController {
@GetMapping("/managers/{id}/employees")
public ResponseEntity<CollectionModel<EntityModel<Employee>>> findEmployees(@PathVariable long id) {
return ResponseEntity.ok(assembler.toCollectionModel(repository.findByManagerId(id)));
CollectionModel<EntityModel<Employee>> collectionModel = assembler
.toCollectionModel(repository.findByManagerId(id));
List<Link> newLinks = collectionModel.getLinks().stream() //
.map(link -> {
// Replace the "self" link so it links back to here
if (link.getRel() == IanaLinkRelations.SELF) {
return linkTo(methodOn(EmployeeController.class).findEmployees(id)).withSelfRel();
} else {
return link;
}
}) //
.collect(Collectors.toList());
return ResponseEntity.ok(new CollectionModel<>(collectionModel.getContent(), newLinks));
}
@GetMapping("/employees/detailed")