java - How to return URLs based on HATEOAS without modifying the whole response? -
i have developed service using spring boot. code (simplified):
@restcontroller @requestmapping("/cars") public class carcontroller { @autowired private carservice carservice; @autowired private carmapper carmapper; @getmapping("/{id}") public cardto findbyid(@pathvariable long id) { car car = carservice.findbyid(id); return carmapper.maptocardto(car); } }
carmapper
defined using mapstruct. here's code (simplified well):
@mapper(componentmodel="spring", uses={ makemodelmapper.class }) public interface carmapper { @mappings({ //fields omitted @mapping(source="listaimagencarro", target="rutasimagenes") }) cardto maptocardto(car car); string car_image_url_format = "/cars/%d/images/%d" /* mapstruct invoke method map car image domain object string. here's issue. */ default string maptourl(carimage carimage) { if (carimage == null) return null; return string.format( car_image_url_format, carimage.getcar().getid(), carimage.getid() ); } }
the json response when invoking service:
{ "id": 9, "make": { ... }, "model": { ... }, //more fields... //the urls car images "images": [ "/cars/9/images/1" ] }
i need images
field returns valid urls regarding server , path app deployed. example, if deploy app using localhost through port 8080, this:
{ "id": 9, "make": { ... }, "model": { ... }, //more fields... "imagenes": [ "http://localhost:8080/cars/9/images/1" ] }
i've reviewed building hypermedia-driven restful web service, seems want. except need these urls, don't want change whole response object.
is there way achieve it?
spring hateoas provides linkbuilder service purpose.
try following:
import static org.springframework.hateoas.mvc.controllerlinkbuilder.linkto; import static org.springframework.hateoas.mvc.controllerlinkbuilder.methodon; //...// linkto(methodon(carcontroller.class).findbyid(9)).withrel("addyourrelhere");
this should output absolute url points resource. not following hal convention, should change or remove part "withrel("")"
you can add specific dtos want change:
cardto dto = carmapper.maptocardto(car); if(dto.matches(criteria)){ dto.seturl(linkto...); } return dto;
by way, of shown in section "create restcontroller" of tutorial mention.
Comments
Post a Comment