跳到主要内容

部分 Entity

有时你的列表 endpoint 返回的 Entity 只包含用于概要展示的部分字段。

ArticleSummary
{
"id": "1",
"title": "first"
}
Article
{
"id": "1",
"title": "first",
"content": "Imagine there was much more here.",
"createdAt": "2011-10-05T14:48:00.000Z"
}

这种情况下,我们可以借助 validateRequired() 重写 Entity.validate(),确保在需要时(详情视图)拿到完整的响应,同时让状态保持 DRY 并经过规范化,以确保数据完整性。

import { validateRequired, Collection, Entity, resource } from '@data-client/rest';
import { Temporal } from 'temporal-polyfill';

export class ArticleSummary extends Entity {
  id = '';
  title = '';

  // this ensures `Article` maps to the same entity
  static key = 'Article';

  static schema = {
    createdAt: Temporal.Instant.from,
  };
}

export class Article extends ArticleSummary {
  content = '';
  createdAt = Temporal.Instant.fromEpochMilliseconds(0);

  static validate(processedEntity) {
    return validateRequired(processedEntity, this.defaults);
  }
}

export const ArticleResource = resource({
  path: '/article/:id',
  schema: Article,
}).extend({
  getList: {
    schema: new Collection([ArticleSummary]),
  },
});
结果
Store▶

将详情数据放在嵌套 Entity 中​

通常更好的做法是把开销大的数据移到另一个 Entity 中,以简化条件逻辑。

resources/Article.ts
class ArticleSummary extends Entity {
id = '';
title = '';
content = '';
createdAt = Temporal.Instant.fromEpochMilliseconds(0);

static schema = {
createdAt: Temporal.Instant.from,
meta: ArticleMeta,
};

// this ensures `Article` maps to the same entity
static key = 'Article';
}

class Article extends ArticleSummary {
meta = ArticleMeta.fromJS();

static validate(processedEntity) {
return validateRequired(processedEntity, this.defaults);
}
}

class ArticleMeta extends Entity {
viewCount = 0;
likeCount = 0;
relatedArticles: ArticleSummary[] = [];

static schema = {
relatedArticles: [ArticleSummary],
};
}

const ArticleResource = resource({
path: '/article/:id',
schema: Article,
}).extend({
getList: { schema: new Collection([ArticleSummary]) },
});