0

渲染FastJsonApi gem serialized_json的默认结果如下:

render json: FlashcardSerializer.new(flashcards).serialized_json

会是这样的:

{
 "data": [
    {
      "id": "1",
      "type": "flashcard",
      "attributes": {
        "question": "why?",
        "answer": "pretty good",
        "slug": null
      }
    },
    {
      "id": "2",
      "type": "flashcard",
      "attributes": {
        "question": "What is 0",
        "answer": "it is 0",
        "slug": null
       }
    }
  ]
}

我宁愿添加一些额外的信息,特别是对于分页,我希望结果是这样的:

{
 "data": [
    {
      "id": "1",
      "type": "flashcard",
      "attributes": {
        "question": "why?",
        "answer": "pretty good",
        "slug": null
      }
    },
    {
      "id": "2",
      "type": "flashcard",
      "attributes": {
        "question": "What is 0",
        "answer": "it is 0",
        "slug": null
       }
    },
    "count":100,
     "page":1,
  ]
}

我知道在 API 中管理分页的其他可用 gem,并且我知道如何在没有 Fastjson 的情况下做到这一点。这里的主要问题是,是否有任何方法可以从这个 gem 中获得上述结果,而无需对代码进行大量更改。谢谢

4

1 回答 1

1

根据 JSON API 规范,所需的文档将是无效的。您需要在链接部分中包含下一个和上一个链接。current和将total_count属于元部分。

{
 "data": [
    {
      "id": "1",
      "type": "flashcard",
      "attributes": {
        "question": "why?",
        "answer": "pretty good",
        "slug": null
      }
    },
    {
      "id": "2",
      "type": "flashcard",
      "attributes": {
        "question": "What is 0",
        "answer": "it is 0",
        "slug": null
       }
    },
  ]
  "meta": {
    "page": { "current": 1, "total": 100 }
  },
  "links": {
    "prev": "/example-data?page[before]=yyy&page[size]=1",
    "next": "/example-data?page[after]=yyy&page[size]=1"
  },
}

在继续设计 API 之前,请查看JSON API 规范。

您可以将这些信息作为选项参数传递给序列化程序

class FlashcardsController < ApplicationController
  def index
    render json: FlashcardSerializer.new(
      flashcards, { links: {}, meta: { page: { current: 1 } }
    ).serialized_json
  end
end

您如何生成数据取决于您使用什么来分页。

如果您设计一个新的 API,我还建议使用基于光标的分页而不是偏移分页,因为它的局限性

https://github.com/Netflix/fast_jsonapi#compound-document https://github.com/Netflix/fast_jsonapi/blob/master/spec/lib/object_serializer_spec.rb#L8-L32

于 2021-02-27T07:55:18.420 回答