JSONAPISerializer
JSONAPISerializer。Serializer のサブクラスです。
プロパティ
alwaysIncludeLinkageData: Boolean
デフォルトでは、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
が同じドキュメントに含まれていない場合でもです。
(リレーションシップがドキュメントに含まれているかどうかに関係なく常に追加される) リレーションシップリンクを追加するには、Serializer 基底クラスの links
メソッドを使用するか、より詳細な制御が必要な場合は shouldIncludeLinkageData
を使用できます。
この API の動作の詳細については、こちらのブログ記事 をご覧ください。
メソッド
keyForAttribute(attr: String): String
属性のキーをカスタマイズするために使用します。デフォルトでは、複合属性名はダッシュ化されます。
たとえば、commentCount
属性を持つ post
モデルの JSON:API ドキュメントは次のようになります。
{
data: {
id: 1,
type: 'posts',
attributes: {
'comment-count': 28
}
}
}
keyForRelationship(key: String): String
リレーションシップのキーをカスタマイズするために使用します。デフォルトでは、複合リレーションシップ名はダッシュ化されます。
たとえば、blogPosts
リレーションシップを持つ author
モデルの JSON:API ドキュメントは次のようになります。
{
data: {
id: 1,
type: 'author',
attributes: {
...
},
relationships: {
'blog-posts': {
...
}
}
}
}
links(model: any): any
このフックを使用して、JSON:API リソースオブジェクトにトップレベルの links
データを追加します。引数は、シリアライズされるモデルです。
// serializers/author.js
import { JSONAPISerializer } from 'miragejs';
export default JSONAPISerializer.extend({
links(author) {
return {
'posts': {
related: `/api/authors/${author.id}/posts`
}
};
}
});
shouldIncludeLinkageData(relationshipKey: String, model: Model): Boolean
リレーションシップごとのリンケージデータの包含を可能にします。alwaysIncludeLinkageData
が十分にきめ細かくない場合に使用します。
export default JSONAPISerializer.extend({
shouldIncludeLinkageData(relationshipKey, model) {
if (relationshipKey === 'author' || relationshipKey === 'ghostWriter') {
return true;
}
return false;
}
});
typeKeyForModel(model: Model): String
ドキュメントの type
フィールドをカスタマイズするために使用します。デフォルトでは、モデルの modelName
が複数形化され、ダッシュ化されます。
たとえば、blogPost
モデルの JSON:API ドキュメントは次のようになります。
{
data: {
id: 1,
type: 'blog-posts'
}
}