且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何通过 HATEOAS 链接访问 REST 集合的一个元素?

更新时间:2023-12-03 08:58:10

简单地说,Traverson 是为了找到一个链接.

Simply put, Traverson is meant to find a link.

在最简单的情况下,每个链接都有一个唯一的名称(rel).通过简单地将 rel 的名称提供给 Traverson 的 follow(...) 函数,它将使用正确的 LinkDiscoverer 并导航到相应的该 rel 的 URI.

In the simplest cases, each link has a unique name (rel). By simply providing the name of the rel to Traverson's follow(...) function, it will use the proper LinkDiscoverer and navigate to the corresponding URI of that rel.

这是一个Hop.

由于目标是像跟踪网页上的链接一样导航 API,因此您必须定义一个跃点链.

Since the goal is to navigate the API kind of like following links on a webpage, you must define a chain of hops.

就您而言,情况稍微复杂一些,因为您嵌入了多个项目.请求 self 链接并不简单,因为您可以轻松地在根文档中看到三个.

In your case, it's a little more complication, since you have an embedded with multiple items. Asking for the self link isn't straightforward, since you can easily see three on the root document.

因此 Traverson 支持 JSON-Path.如果您查看参考文档,很容易看出可以提供 JSON-Path 表达式来帮助选择您想要的链接.

Hence Traverson's support for JSON-Path. If you check the reference documentation, it's easy to see that a JSON-Path expression can be supplied to help pick which link you want.

只要选择的属性是 URI,Traverson 就会跳"到它.

As long as the attribute being selected is the URI, then Traverson will "hop" to it.

注意:当简单地使用 rels 时,您可以在 follow(...) 中提供多个 rels 作为字符串.当使用其他任何东西时,例如 JSON-Path 表达式或 rel(...),然后使用一个 follow(...) 每跳.值得庆幸的是,这并不难理解你将每一跳放在单独的行上(同样,请参阅参考文档以获取示例).

NOTE: When simply using rels, you can supply multiple rels as strings in follow(...). When using anything else, like a JSON-Path expression or rel(...), then use one follow(...) per hop. Thankfully, this isn't hard to read of you put each hop on a separate line (again, see ref docs for examples).