首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Rails -如何向Fastjson api添加分页?

Rails -如何向Fastjson api添加分页?
EN

Stack Overflow用户
提问于 2021-02-26 22:27:37
回答 1查看 194关注 0票数 0

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

代码语言:javascript
复制
render json: FlashcardSerializer.new(flashcards).serialized_json

应该是这样的:

代码语言:javascript
复制
{
 "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
       }
    }
  ]
}

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

代码语言:javascript
复制
{
 "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,
  ]
}

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

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-02-27 15:55:18

所需的文档应该是invalid according to the JSON API specification。您需要在链接部分中包含下一个和前一个链接。currenttotal_count将属于meta部分。

代码语言:javascript
复制
{
 "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"
  },
}

在继续设计JSON API specification之前,先看一下API。

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

代码语言:javascript
复制
class FlashcardsController < ApplicationController
  def index
    render json: FlashcardSerializer.new(
      flashcards, { links: {}, meta: { page: { current: 1 } }
    ).serialized_json
  end
end

生成数据的方式取决于用于分页的内容。

如果你设计了一个新的应用程序接口,我也建议你使用基于指针的分页而不是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

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/66387607

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档