【问题标题】:Proper way to handle a large amount of relationship resources of a resource in JSON:API format (Content-Type application/vnd.api+json)JSON:API格式(Content-Type application/vnd.api+json)的资源的大量关系资源处理的正确方法
【发布时间】:2020-01-21 16:58:30
【问题描述】:

我正在构建一个 api,我正在尝试处理以下问题:

客户端用application/vnd.api+json发送Accept头,所以我回复JSON:API格式的资源。

例如以下表格:

  • 作者
  • 文章

具有 1:n 关系 - 例如,一位作者写了 100 篇文章

我的目标是:

获取/作者

返回作者(资源对象)定义数量的文章(关系资源对象) - 例如他写的前 3 篇文章。

采用这种格式:

{
  "links": {
    "self": "http://example.com/author",
    "next": "http://example.com/author?page[offset]=2",
    "last": "http://example.com/author?page[offset]=10"
  },
  "data": [
    {
      "type": "author",
      "id": "1",
      "attributes": {
        "name": "Arthur"
      },
      "relationships": {
        "article": {
          "count": 100,
          "links": {
            "self": "http://example.com/author/1/relationships/article",
            "related": "http://example.com/author/1/article"
          },
          "data": [
            {
              "type": "article",
              "id": "4",
              "attributes": {
                "title": "1 reason why I should use json:api"
              },
              "links": {
                "self": "http://example.com/article/4"
              }
            },
            {
              "type": "article",
              "id": "7",
              "attributes": {
                "title": "2 reasons why I should use json:api"
              },
              "links": {
                "self": "http://example.com/article/7"
              }
            },
            {
              "type": "article",
              "id": "42",
              "attributes": {
                "title": "3 reasons why I should use json:api"
              },
              "links": {
                "self": "http://example.com/article/42"
              }
            }
          ]
        }
      }
    }
  ]
}

我的想法:

使用类似的查询参数

http://example.com/author?relationship[]=article,orderby=date,asc=true,limit=3

tl;博士:

以 JSON:API 格式限制/分页相关资源的正确方法是什么?

【问题讨论】:

    标签: rest api json-api jsonapi-resources


    【解决方案1】:

    该规范不包括所包含的相关资源的分页和排序。如果您需要对它们进行分页或排序,我建议不要包含相关资源,而是使用关系链接。缺点是有一个额外的请求......

    除此之外,我注意到您的回复不是对 JSON:API 的抱怨。对于resource linkage,必须使用resource identifier object(has-one)或资源标识符对象列表(has-many)。

    您正在使用完整的资源对象。区别在于attributeslinks 键。链接的资源对象可以使用compound document 包含在响应中。

    您使用查询参数来允许客户端控制相关资源的包含的想法实际上是规范的一部分。因此,它使用include 查询参数。这在规范的Inclusion of Related Resources 章节中有详细描述。但如前所述,这不包括所包含资源的分页和排序。

    【讨论】:

    • 感谢您的回复——对我帮助很大!
    • @Tries 如果您在这种情况下接受它以帮助其他人找到解决问题的方法,那就太好了。 :-)
    猜你喜欢
    • 2021-12-10
    • 2018-08-19
    • 2010-11-10
    • 2021-12-29
    • 1970-01-01
    • 1970-01-01
    • 2013-03-13
    • 2021-09-10
    • 1970-01-01
    相关资源
    最近更新 更多