为特定单个资源的集合资源生成链接



我编写了一个自定义控制器来处理GET http://localhost:54000/api/v1/portfolios/{id}/evaluate请求。

@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);
}

当前响应为

{
  "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"
    }
  }
}

但我想添加与该投资组合相关的收集资源(摘要和系统):

{
  "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"
    }
  }
}

我没有找到使用RepositoryEntityLinks entityLinks对象生成这些链接的方法

你总是可以这样做:

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

如果您的系统端点是在自定义控制器方法中实现的,则可以使用ControllerLinkBuilder生成指向控制器方法的链接。假设您在MyControllerClass中使用id参数实现了getSystems方法,然后您可以生成这样的链接(linkTo和methodOn是ControllerLinkBuilder中的静态方法):

linkTo(methodOn(MyControllerClass.class).getSystems(id)).withRel("systems");

最新更新