JSONAPISerializer
JSONAPISerializer。Serializer 的子類別。
屬性
alwaysIncludeLinkageData: 布林值
預設情況下,JSON:API 的連結資料僅會為當前請求中包含的關係新增。
這表示給定一個具有 posts
關係的 author
模型,對 /authors/1 的 GET 請求會傳回一個具有空的 relationships
雜湊的 JSON:API 文件
{
data: {
type: 'authors',
id: '1',
attributes: { ... }
}
}
但對 GET /authors/1?include=posts 的請求會新增連結資料(除了包含的資源之外)
{
data: {
type: 'authors',
id: '1',
attributes: { ... },
relationships: {
data: [
{ type: 'posts', id: '1' },
{ type: 'posts', id: '2' },
{ type: 'posts', id: '3' }
]
}
},
included: [ ... ]
}
若要為所有關係新增連結資料,您可以將 alwaysIncludeLinkageData
設定為 true
JSONAPISerializer.extend({
alwaysIncludeLinkageData: true
});
然後,對 /authors/1 的 GET 請求會回應
{
data: {
type: 'authors',
id: '1',
attributes: { ... },
relationships: {
posts: {
data: [
{ type: 'posts', id: '1' },
{ type: 'posts', id: '2' },
{ type: 'posts', id: '3' }
]
}
}
}
}
即使相關的 posts
沒有包含在同一個文件中。
您也可以使用 links
方法(在 Serializer 基底類別上)來新增關係連結(無論關係是否包含在文件中,都會始終新增),或者您可以使用 shouldIncludeLinkageData
來進行更精細的控制。
如需此 API 行為的更多背景資訊,請參閱這篇部落格文章。
方法
keyForAttribute(attr: 字串): 字串
用於自訂屬性的鍵。預設情況下,複合屬性名稱會轉換為破折號。
例如,具有 commentCount
屬性的 post
模型的 JSON:API 文件會是
{
data: {
id: 1,
type: 'posts',
attributes: {
'comment-count': 28
}
}
}
keyForRelationship(key: 字串): 字串
用於自訂關係的鍵。預設情況下,複合關係名稱會轉換為破折號。
例如,具有 blogPosts
關係的 author
模型的 JSON:API 文件會是
{
data: {
id: 1,
type: 'author',
attributes: {
...
},
relationships: {
'blog-posts': {
...
}
}
}
}
links(model: 任何): 任何
使用此掛鉤將最上層的 links
資料新增至 JSON:API 資源物件。參數是正在序列化的模型。
// serializers/author.js
import { JSONAPISerializer } from 'miragejs';
export default JSONAPISerializer.extend({
links(author) {
return {
'posts': {
related: `/api/authors/${author.id}/posts`
}
};
}
});
shouldIncludeLinkageData(relationshipKey: 字串, model: 模型): 布林值
允許每個關係包含連結資料。當 alwaysIncludeLinkageData
不夠精細時,請使用此方法。
export default JSONAPISerializer.extend({
shouldIncludeLinkageData(relationshipKey, model) {
if (relationshipKey === 'author' || relationshipKey === 'ghostWriter') {
return true;
}
return false;
}
});
typeKeyForModel(model: 模型): 字串
用於自訂文件的 type
欄位。預設情況下,會將模型的 modelName
轉換為複數並加上破折號。
例如,blogPost
模型的 JSON:API 文件會是
{
data: {
id: 1,
type: 'blog-posts'
}
}