I am learning how to use Spring Boot to build REST APIs through a written tutorial and HATEOAS is used at some point. It seems the tutorial uses a now outdated version (0.x) since the classes Resource, Resources, ControllerLinkBuilder etc. weren't being found, so after some digging I found out 1.x had modified the structure and naming of some classes. I just swapped out every mention of a class/method with its updated version (Resource with EntityModel, etc.) and didn't run into much trouble until I got stuck at the part where a resource's "self" link was needed to generate an HTTP response for the POST command:
@PostMapping("/employees")
ResponseEntity<?> newEmployee(@RequestBody Employee newEmployee) throws URISyntaxException {
Resource<Employee> resource = assembler.toResource(repository.save(newEmployee));
return ResponseEntity
.created(new URI(resource.getId().expand().getHref()))
.body(resource);
}
Is there an equivalent for
resource.getId()
For EntityModel in HATEOAS 1.x?
This is the class the "assembler" variable is an instance of:
package payroll;
import static org.springframework.hateoas.server.mvc.WebMvcLinkBuilder.*;
import org.springframework.hateoas.EntityModel;
import org.springframework.hateoas.server.RepresentationModelAssembler;
import org.springframework.stereotype.Component;
@Component
class EmployeeResourceAssembler implements RepresentationModelAssembler<Employee, EntityModel<Employee>> {
@Override
public EntityModel<Employee> toModel(Employee employee) {
return new EntityModel<>(employee,
linkTo(methodOn(EmployeeController.class).one(employee.getId())).withSelfRel(),
linkTo(methodOn(EmployeeController.class).all()).withRel("employees"));
}
}
Found it, that was equivalent to doing this in HATEOAS 1.x:
return ResponseEntity
.created(new URI(resource.getLink("self").orElse(new Link("self")).getHref()))
.body(resource);
Since getLink()
returns an Optional<Link>
I just had to add orElse()
case so that it's "unwrapped".