【问题标题】:How to access one element of a REST collection through HATEOAS links?如何通过 HATEOAS 链接访问 REST 集合的一个元素?
【发布时间】:2019-04-13 20:23:30
【问题描述】:

我正在尝试使用 Java Spring 构建 RESTful 服务架构,并为所有这些构建网关服务。为了实现后者,我需要为其他服务实现一个客户端,我和我的同事试图围绕 HATEOAS 原则进行设计,通过 spring-hateoas 模块提供相关资源的链接。

假设我有一个在 localhost 上运行的服务,监听 8080 端口,它返回一个资源集合,并在 /resources 上执行 GET 操作。例如:

{
  "_embedded" : {
    "resources" : [ {
      "label" : "My first resource!",
      "resourceId" : 3,
      "_links" : {
        "self" : {
          "href" : "http://localhost:8080/resources/3"
        },
        "meals" : {
          "href" : "http://localhost:8080/resources",
          "templated" : true
        }
      }
    }, {
      "label" : "Another resource!",
      "resourceId" : 4,
      "_links" : {
        "self" : {
          "href" : "http://localhost:8080/resources/4"
        },
        "meals" : {
          "href" : "http://localhost:8080/resources",
          "templated" : true
        }
      }
    } ]
  },
  "_links" : {
    "self" : {
      "href" : "http://localhost:8080/resources",
      "templated" : true
    }
  }
}

我正在尝试使用 HATEOAS 客户端,例如 Traverson。我怎么能简单地通过关注 HATEOAS 链接来关注资源元素?到目前为止,我的解决方案是在我的收藏中添加指向item 的链接,如下所示:

"_links" : {
    "self" : {
      "href" : "http://localhost:8080/resources",
      "templated" : true
    },
    "item" : {
      "href" : "http://localhost:8080/resources/{id}",
      "templated" : true
    }
}

那么我可以直接用 Traverson 替换模板中的 id 并按照结果进行操作。但这是一个好习惯吗?我应该采取其他方式吗?

【问题讨论】:

  • 这个问题听起来很像this oneIMO

标签: spring rest hateoas spring-hateoas


【解决方案1】:

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

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

这是Hop

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

在您的情况下,这有点复杂,因为您嵌入了多个项目。请求self 链接并不简单,因为您可以很容易地在根文档中看到三个。

因此 Traverson 支持 JSON-Path。如果您查看reference documentation,很容易看到可以提供 JSON-Path 表达式来帮助选择您想要的链接。

只要选择的属性是 URI,那么 Traverson 就会“跳”到它。

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

【讨论】:

  • 我发现我的解决方案并没有那么糟糕 :) 我会检查 JSON 路径的使用,看看我是否可以让它更漂亮。谢谢!
猜你喜欢
  • 2014-01-04
  • 2016-05-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-06-22
  • 1970-01-01
  • 1970-01-01
  • 2016-12-11
相关资源
最近更新 更多