渲染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,
]
}我知道有其他可用的gem可以在API中管理分页,而且我知道如何在没有Fastjson的情况下做到这一点。这里的主要问题是,是否有任何方法可以在不对代码进行太多更改的情况下从这个gem获得上述结果。谢谢
发布于 2021-02-27 15:55:18
所需的文档应该是invalid according to the JSON API specification。您需要在链接部分中包含下一个和前一个链接。current和total_count将属于meta部分。
{
"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。
可以将这些信息作为选项参数传递到序列化程序中
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
https://stackoverflow.com/questions/66387607
复制相似问题