0

I wrote a custom controller to handle a GET http://localhost:54000/api/v1/portfolios/{id}/evaluate request.

@RequestMapping(value = "/portfolios/{id}/evaluate", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<?> evaluate(@PathVariable Long id) {
    Portfolio portfolio = portfolioService.evaluate(id);
    if (portfolio == null) {
        return ResponseEntity.notFound().build();
    }
    Resource<Portfolio> resource = new Resource<>(portfolio);
    resource.add(entityLinks.linkForSingleResource(Portfolio.class, id).withSelfRel());
    return ResponseEntity.ok(resource);
}

The current response is

{
  "summary" : {
    "count" : 24.166666666666668,
    "yield" : 0.14921630094043895,
    "minBankroll" : -6.090909090909091,
    "sharpeRatio" : 0.7120933654645042,
    "worstReturn" : -2.4545454545454533,
    "losingSeason" : 3,
    "return" : 3.6060606060606077
  },
  "_links" : {
    "self" : {
      "href" : "http://localhost:54000/api/v1/portfolios/4"
    }
  }
}

but I would like to add collection resources (summaries and systems) linked to that portfolio:

{
  "summary": {
    "count": 24.166666666666668,
    "yield": 0.14921630094043895,
    "minBankroll": -6.090909090909091,
    "sharpeRatio": 0.7120933654645042,
    "worstReturn": -2.4545454545454533,
    "losingSeason": 3,
    "return": 3.6060606060606077
  },
  "_links": {
    "self": {
      "href": "http://localhost:54000/api/v1/portfolios/4"
    },
    "portfolio": {
      "href": "http://localhost:54000/api/v1/portfolios/4"
    },
    "summaries": {
      "href": "http://localhost:54000/api/v1/portfolios/4/summaries"
    },
    "systems": {
      "href": "http://localhost:54000/api/v1/portfolios/4/systems"
    }
  }
}

I did not find a way to generate those links with the RepositoryEntityLinks entityLinks object

Sydney
  • 11,964
  • 19
  • 90
  • 142

1 Answers1

1

You can always do something like this:

entityLinks.linkForSingleResource(Portfolio.class, id).slash("systems").withRel("systems");

And if your systems endpoint is implemented in a custom controller method you can use the ControllerLinkBuilder to generate a link to your controller method. Lets say you implemented the getSystems method with id parameter in MyControllerClass - then you can generate the link like this (linkTo and methodOn are static methods in ControllerLinkBuilder):

linkTo(methodOn(MyControllerClass.class).getSystems(id)).withRel("systems");
Mathias Dpunkt
  • 11,594
  • 4
  • 45
  • 70