关系型数据
在 Entity.schema 中声明 Entity 之间的一对一、多对一和多对多关系。
嵌套
当 Entity 定义了 Entity.schema 时,规范化会把每个嵌套的 Entity 单独存储。反规范化会把它们重新组合起来。
示意图
import { Collection, Entity, resource } from '@data-client/rest'; export class User extends Entity { id = ''; name = ''; } export class Comment extends Entity { id = ''; content = ''; commenter = User.fromJS(); static schema = { commenter: User, }; } export class Post extends Entity { id = ''; title = ''; author = User.fromJS(); comments: Comment[] = []; static schema = { author: User, comments: new Collection([Comment], { nestKey: (parent, key) => ({ postId: parent.id, }), }), }; } export const PostResource = resource({ path: '/posts/:id', schema: Post, });
客户端 join
在 endpoint 不嵌套数据时实现嵌套。
当响应没有嵌套关联数据时,请在 Entity.schema 中声明关联关系。 Data Client 随后会在客户端组合这些数据。
这里 /todos 只发送每个 todo 的 userId。Entity.process() 让
user 指向该 id,因此列表中的每个 todo 都带有来自 /users 的完整 User。组件本可以自己按 id 查找某个用户;而 join 把用户放进了列表中,于是列表可以按人分组。把任务分配给其他人(点选他们的头像,或把任务拖进他们的分组),只有新的 userId 会发送到服务器,但任务仍会移动到那个人的分组中。
import { Entity, resource } from '@data-client/rest'; import { User } from './User'; export class Todo extends Entity { id = 0; userId = 0; user? = User.fromJS(); title = ''; completed = false; // the API sends userId; join it to the User with that id static schema = { user: User, }; static process(todo) { return { ...todo, user: todo.userId }; } } export const TodoResource = resource({ urlPrefix: 'https://jsonplaceholder.typicode.com', path: '/todos/:id', schema: Todo, optimistic: true, });
基于键的 join
当关联 Entity 来自不同的获取时,使用 Entity.process() 添加一个引用另一个 Entity 的键。在以下情况中使用它:
- 关联数据来自不同的 API endpoint。
- 你不想获取不需要的嵌套数据。
- 关联关系是可选的,或取决于上下文。
import { Entity, resource } from '@data-client/rest';
class Stats extends Entity {
product_id = '';
volume = 0;
price = 0;
pk() {
return this.product_id;
}
static key = 'Stats';
}
class Currency extends Entity {
id = '';
name = '';
// Default value allows Currency to exist without Stats loaded
stats = Stats.fromJS();
pk() {
return this.id;
}
static key = 'Currency';
// Create a reference key that links to Stats entity
static process(input: any, parent: any, key: string, args: any[]) {
// The stats field becomes a reference to Stats with pk `${id}-USD`
return { ...input, stats: `${input.id}-USD` };
}
static schema = {
// Stats will be looked up by the key from process()
stats: Stats,
};
}
在 CurrencyResource.getList 和 StatsResource.getList 都 resolve 之后,stats 就是对应的 Stats Entity。
加密货币价格示例
这个列表按交易量对 Currencies 排序。只有 Stats Entity 包含交易量,而
CurrencyResource.getList 的响应中不包含它。因此页面还会获取 StatsResource.getList,并由
Currency 的 Entity.schema 把 Stats 添加到每个 Currency 上。这样列表就可以排序:
entries.sort((a, b) => {
return b?.stats?.volume_usd - a?.stats?.volume_usd;
});
探索 coin-app 示例
反向查找
在 endpoint 不嵌套数据时实现嵌套(第二部分)。
响应只能在一个方向上嵌套。这里 /posts 嵌套了每个 post 的 author,但没有任何响应列出某个 user 的
posts。反向查找会在客户端构建这个列表,因此一次获取 /posts 也能得到每个 user 的 posts
和 comments。点击名字即可查看。
import { Entity, resource, type Schema } from '@data-client/rest'; export class User extends Entity { id = ''; name = ''; posts: Post[] = []; comments: Comment[] = []; static process(value, parent, key) { switch (key) { // nested as a post's author: that post is one of this user's case 'author': return { ...value, posts: [parent.id] }; // nested as a comment's commenter case 'commenter': return { ...value, comments: [parent.id] }; default: return { ...value }; } } // one user is nested many times, each with one post or comment static merge(existing, incoming) { return { ...existing, ...incoming, posts: union(existing.posts, incoming.posts), comments: union(existing.comments, incoming.comments), }; } } /** Adds the ids not listed yet, so a refetch does not add the same ones again. * Does not remove repeats within `incoming`: here each copy of a user brings one id. */ function union(existing: string[] = [], incoming: string[] = []) { const added = incoming.filter(id => !existing.includes(id)); return added.length ? [...existing, ...added] : existing; } export class Comment extends Entity { id = ''; content = ''; commenter = User.fromJS(); post = Post.fromJS(); static schema: Record<string, Schema> = { commenter: User, }; static process(value, parent, key) { // only a post's `comments` tells which post this comment is on return key === 'comments' ? { ...value, post: parent.id } : { ...value }; } } export class Post extends Entity { id = ''; title = ''; author = User.fromJS(); comments: Comment[] = []; static schema = { author: User, comments: [Comment], }; } // the classes refer to each other, so set these after all are defined User.schema = { posts: [Post], comments: [Comment], }; Comment.schema = { ...Comment.schema, post: Post, }; export const PostResource = resource({ path: '/posts/:id', schema: Post, }); export const UserResource = resource({ path: '/users/:id', schema: User, });
User 覆盖了两个方法。process() 会针对每个嵌套的 user 运行,并接收嵌套它的 parent
和 key。merge() 会合并同一个 user 的多个副本:
// post 1 nests Paul as its `author`, so process() adds that post's id
User.process({ id: '123', name: 'Paul' }, post1, 'author');
// => { id: '123', name: 'Paul', posts: ['1'] }
// post 2 nests Paul too, so merge() joins both copies
User.merge(
{ id: '123', name: 'Paul', posts: ['1'] },
{ id: '123', name: 'Paul', posts: ['2'] },
);
// => { id: '123', name: 'Paul', posts: ['1', '2'] }
如果不覆盖,merge() 只会保留最后一个副本的 posts。Comment.process() 也以同样的方式设置 comment.post。
何时使用
当数据本身(而不只是界面)必须拥有某个列表时,才在 Entity 中嵌套它。例如,一个按 user.posts 对用户排序的 Query 会在任何组件渲染之前读取它。然后根据列表所在的位置来选择:
- 某个响应包含该列表(user 响应嵌套了它,或者
GET /posts?author=123返回了它):使用带 nestKey 的 Collection。每次获取都会替换该列表,而 push、remove 和 move 会让它保持最新。它不需要自定义merge()。 - 没有任何响应包含该列表:使用反向查找。
变更之后
- 创建。 新的 post 或 comment 会运行同样的
process(),因此会加入该列表。这对 push 和每个新页面都成立。 - 删除。 被删除的 post 或 comment 会离开该列表。列表会跳过不在 store 中的 Entity。
- 移动。 拥有新
author的 post 会加入新作者的posts,同时仍留在旧作者的列表中:merge()只会添加 id。当关联关系可能移动时,请在读取列表的地方,用基于 All 的 Query 来计算它。
循环依赖
JavaScript 不允许循环导入或循环的类定义。因此对于相互引用的 Entity,请在类定义之后再定义 schema。
import { Entity } from '@data-client/rest';
import { User } from './User';
export class Post extends Entity {
id = '';
title = '';
author = User.fromJS();
static schema = {
author: User,
};
}
// both User and Post are now defined, so it's okay to refer to both of them
User.schema = {
// ensure we keep the 'createdAt' member
...User.schema,
posts: [Post],
};
import { Entity, type Schema } from '@data-client/rest';
import { Temporal } from 'temporal-polyfill';
// import only the type: importing the class would be a circular import,
// so resources/Post sets User.schema above
import type { Post } from './Post';
export class User extends Entity {
id = '';
name = '';
posts: Post[] = [];
createdAt = Temporal.Instant.fromEpochMilliseconds(0);
static schema: Record<string, Schema> = {
createdAt: Temporal.Instant.from,
};
}