【问题标题】:Rails - How to add pagination to Fastjson api?Rails - 如何向 Fastjson api 添加分页?
【发布时间】:2021-05-28 22:33:24
【问题描述】:

FastJsonApi gemserialized_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 中获得上述结果,而无需对代码进行大量更改。谢谢

【问题讨论】:

    标签: ruby-on-rails fastjsonapi


    【解决方案1】:

    所需的文档是invalid according to the JSON API specification。您需要在链接部分中包含下一个和上一个链接。 currenttotal_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 specification

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

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

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

    如果您设计一个新的 API,我还建议使用基于光标的分页而不是 offset pagination because of it's limitations

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

    【讨论】:

      猜你喜欢
      • 2014-10-19
      • 2014-05-10
      • 1970-01-01
      • 1970-01-01
      • 2019-04-03
      • 1970-01-01
      • 2014-07-17
      • 1970-01-01
      • 2019-06-03
      相关资源
      最近更新 更多