From 287995aa1ad996d4c6e27725e6af8016bf8edf53 Mon Sep 17 00:00:00 2001 From: Greg Turnquist Date: Thu, 12 Dec 2019 11:15:46 -0600 Subject: [PATCH] For manager-based employee aggregate, swap out default "self link. Resolves: #29 --- .../hateoas/examples/EmployeeController.java | 21 ++++++++++++++++++- 1 file changed, 20 insertions(+), 1 deletion(-) diff --git a/hypermedia/src/main/java/org/springframework/hateoas/examples/EmployeeController.java b/hypermedia/src/main/java/org/springframework/hateoas/examples/EmployeeController.java index 2242f3e..dfc68c6 100644 --- a/hypermedia/src/main/java/org/springframework/hateoas/examples/EmployeeController.java +++ b/hypermedia/src/main/java/org/springframework/hateoas/examples/EmployeeController.java @@ -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>> findEmployees(@PathVariable long id) { - return ResponseEntity.ok(assembler.toCollectionModel(repository.findByManagerId(id))); + CollectionModel> collectionModel = assembler + .toCollectionModel(repository.findByManagerId(id)); + + List 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")