包括符合 JSON API 规范的非关联对象响应
Include non-associated objects response which conforms JSON API specification
我正在尝试使用 JSON API specification
在 rails 中构建一个 API
我的用户模型有与之关联的更改对象。例如,用户可以进行以下更改:
{
id: 10,
type: 'changes',
diffs: [
{
subject: 'email',
from: 'old@example.org',
to: 'new@example.org'
},
{
subject: 'tags',
from: []
to: [{ id: 1, type: 'tags', label: 'Ruby' }]
}
]
}
如您所见,diffs
属性 包含变化差异数组,第二个差异是对象差异数组。我想修改此格式(如果可能),使其符合 JSON API 规范。像这样:
{
subject: 'tags',
from: []
to: [{ id: 1, type: 'tags' }]
}
并将标签的属性放入包含部分:
included: [
{
id: 1,
type: 'tags',
attributes: { label: 'Ruby' }
}
]
问题: 差异是一个对象数组(不是记录,它们没有 ID),其中包含带记录的字段。是否可以将响应格式化为深度嵌套的记录(如我的情况下的标签)将引用包含部分中的记录?
我想使用 fast_jsonapi gem
我不认为你可以在不违反规范的情况下做到这一点。
A resource object 必须包含一个 id:
“Resource objects” appear in a JSON API document to represent resources.
A resource object MUST contain at least the following top-level members:
- id
- type
规范只允许一个例外:
Exception: The id member is not required when the resource object originates at the client and represents a new resource to be created on the server.
因此,如果您的 diffs
没有 ID,您就无法将它们建模为资源对象。
但是您不能包含未被资源对象引用的资源:
Compound documents require “full linkage”, meaning that every included resource MUST be identified by at least one resource identifier object in the same document. (source)
只有一个例外不适用于此处讨论的案例:
The only exception to the full linkage requirement is when relationship fields that would otherwise contain linkage data are excluded via sparse fieldsets.
我正在尝试使用 JSON API specification
在 rails 中构建一个 API我的用户模型有与之关联的更改对象。例如,用户可以进行以下更改:
{
id: 10,
type: 'changes',
diffs: [
{
subject: 'email',
from: 'old@example.org',
to: 'new@example.org'
},
{
subject: 'tags',
from: []
to: [{ id: 1, type: 'tags', label: 'Ruby' }]
}
]
}
如您所见,diffs
属性 包含变化差异数组,第二个差异是对象差异数组。我想修改此格式(如果可能),使其符合 JSON API 规范。像这样:
{
subject: 'tags',
from: []
to: [{ id: 1, type: 'tags' }]
}
并将标签的属性放入包含部分:
included: [
{
id: 1,
type: 'tags',
attributes: { label: 'Ruby' }
}
]
问题: 差异是一个对象数组(不是记录,它们没有 ID),其中包含带记录的字段。是否可以将响应格式化为深度嵌套的记录(如我的情况下的标签)将引用包含部分中的记录?
我想使用 fast_jsonapi gem
我不认为你可以在不违反规范的情况下做到这一点。
A resource object 必须包含一个 id:
“Resource objects” appear in a JSON API document to represent resources.
A resource object MUST contain at least the following top-level members:
- id
- type
规范只允许一个例外:
Exception: The id member is not required when the resource object originates at the client and represents a new resource to be created on the server.
因此,如果您的 diffs
没有 ID,您就无法将它们建模为资源对象。
但是您不能包含未被资源对象引用的资源:
Compound documents require “full linkage”, meaning that every included resource MUST be identified by at least one resource identifier object in the same document. (source)
只有一个例外不适用于此处讨论的案例:
The only exception to the full linkage requirement is when relationship fields that would otherwise contain linkage data are excluded via sparse fieldsets.