Union
描述一个由多个 schema 联合而成的 schema。当你需要 schema.Array 或 Values 提供的多态行为,但用于非集合字段时,它会很有用。
definition: 必填 一个对象,映射输入数组中嵌套 Entity 的定义schemaAttribute: 必填 每个 Entity 上的属性,它根据定义映射决定规范化时使用哪个 schema。可以是字符串或函数。如果是函数,它接收以下参数:value: 该 Entity 的输入值。parent: 输入数组的父对象。key: 输入数组在父对象上所在的键。
实例方法
define(definition): 调用时,传入的definition会与传给Union构造函数的原始定义合并。这个方法通常用于在 schema 中创建循环引用。
命名
Union 得名于集合论中的概念,就像 TypeScript 联合类型
用法
备注
如果你的数据返回了一个没有提供映射的对象,结果中会返回原始对象,且不会创建 Entity。
Fixtures
GET /feed
[{"id":1,"type":"link","url":"https://ntucker.true.io","title":"Nate site"},{"id":10,"type":"post","content":"good day!"}]
▶api/Feed
import { Entity, RestEndpoint, Union } from '@data-client/rest'; export abstract class FeedItem extends Entity { readonly id: number = 0; declare readonly type: 'link' | 'post'; } export class Link extends FeedItem { readonly type = 'link' as const; readonly url: string = ''; readonly title: string = ''; } export class Post extends FeedItem { readonly type = 'post' as const; readonly content: string = ''; } export const getFeed = new RestEndpoint({ path: '/feed', schema: [ new Union( { link: Link, post: Post, }, 'type', ), ], });
▶FeedList
结果
Store▶
函数形式的 schemaAttribute
当判别值无法直接匹配 schema 的键时,使用函数来计算应使用哪个 schema。
Fixtures
GET /feed
[{"id":1,"type":"link","url":"https://ntucker.true.io","title":"Nate site"},{"id":10,"type":"post","content":"good day!"}]
▶api/Feed
import { Entity, RestEndpoint, Union } from '@data-client/rest'; export abstract class FeedItem extends Entity { readonly id: number = 0; declare readonly type: 'link' | 'post'; } export class Link extends FeedItem { readonly type = 'link' as const; readonly url: string = ''; readonly title: string = ''; } export class Post extends FeedItem { readonly type = 'post' as const; readonly content: string = ''; } export const getFeed = new RestEndpoint({ path: '/feed', schema: [ new Union( { links: Link, posts: Post, }, (input: Link | Post, parent: unknown, key: string) => `${input.type}s`, ), ], });
▶FeedList
结果
Store▶
Github Events
贡献动态来自按类型对 github 事件的分组。每种 Event 都有各自独立的 schema,这就是我们使用 Union 的原因
探索 github-app 示例