JSONAPISerializer

JSONAPISerializer 类。Serializer 类的子类。

属性

alwaysIncludeLinkageData: Boolean

默认情况下,JSON:API 的关联数据仅在当前请求包含关系时才会添加。

这意味着给定一个具有 posts 关系的 author 模型,对 /authors/1 的 GET 请求将返回一个 JSON:API 文档,其中包含一个空的 relationships 哈希。

{
  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: 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': {
        ...
      }
    }
  }
}

使用此钩子向 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'
  }
}