跳到主要内容

Endpoint

Endpoint 适用于任何异步函数(即返回 Promise 的函数)。

Endpoints 定义了一套强类型的标准接口,描述相关的元数据和生命周期,可供 Reactive Data Client 及其他 store 使用。

包:@data-client/endpoint

提示

Endpoint 是一个与协议无关的类。建议改用针对特定协议的模式: REST、GraphQL 或 getImage。

接口
export interface EndpointInterface<
F extends FetchFunction = FetchFunction,
S extends Schema | undefined = Schema | undefined,
M extends true | undefined = true | undefined,
> extends EndpointExtraOptions<F> {
(...args: Parameters<F>): InferReturn<F, S>;
key(...args: Parameters<F>): string;
readonly sideEffect?: M;
readonly schema?: S;
}

用法​

Endpoint 让现有的异步函数可以在任何 Reactive Data Client 上下文中使用,并享有完整的 TypeScript 类型约束。

import { Endpoint } from '@data-client/rest';
import { Todo } from './interface';

const getTodoOriginal = (id: number): Promise<Todo> =>
  Promise.resolve({
    id,
    title: 'delectus aut autem ' + id,
    completed: false,
    userId: 1,
  });

export const getTodo = new Endpoint(getTodoOriginal);
import { useSuspense } from '@data-client/react';
import { getTodo } from './api';

function TodoDetail() {
  const todo = useSuspense(getTodo, 1);
  return <div>{todo.title}</div>;
}
render(<TodoDetail />);
实时预览

共享配置​

请使用 Endpoint.extend(),而不是 {...getTodo}(展开)

const getTodoNormalized = getTodo.extend({ schema: Todo });
const getTodoUpdatingEveryFiveSeconds = getTodo.extend({ pollFrequency: 5000 });

取消及其他非键值​

参数就是 key:它们决定 store 保存哪份数据。不要把不选择数据的值(例如 AbortSignal 或 SDK 客户端)放进参数。如果作为参数,每次 hook 调用都需要传一个,而且带与不带它的调用会得到不同的 key,因而无法共享数据。请把这类值改为成员,并在 fetch 函数中从 this 读取它。signal 已经有类型;其他成员请在选项中声明。

getPosts
import { Endpoint } from '@data-client/endpoint';
import { client } from './client';
import { Post } from './Post';

export const getPosts = new Endpoint(
// a `function` (not an arrow function) gets the endpoint as `this`
function ({ page }: { page: number }) {
return client.getPosts({ page, signal: this.signal });
},
{ name: 'getPosts', schema: [Post] },
);

用 extend() 为单次调用设置该成员,这样其他调用仍保留各自的值。

// ctrl is the Controller, from useController() or a router loader
const abort = new AbortController();
ctrl.fetch(getPosts.extend({ signal: abort.signal }), { page: 2 });

useCancelling() 会替你完成这件事,并在参数变化时中止:

PostList
import { useCancelling, useSuspense } from '@data-client/react';
import { getPosts } from './getPosts';
import PostItems from './PostItems';

export default function PostList({ page }: { page: number }) {
const posts = useSuspense(useCancelling(getPosts, { page }), { page });
return <PostItems posts={posts} />;
}

限制:

  • 只有当 fetch 函数把 signal 继续传递下去,并且 SDK 把它交给 fetch() 时,请求才会停止。
  • 参数相同的读取(没有 sideEffect)会共享同一个请求。signal 只能取消由它自己的调用发起的请求,而且这会为所有共享该请求的调用取消它。
  • Data Client 会忽略名为 AbortError 的 rejection,这正是 fetch() 抛出的错误。如果你的 SDK 把中止包装成了其他错误,请重新抛出一个名为 AbortError 的错误;否则它会被存储为失败的 fetch,使用这些参数的渲染会一直抛出它,直到它过期。
  • 中止一个变更会撤销它的乐观更新,但服务器可能已经应用了该变更。

生命周期​

成功​

错误​

Endpoint 成员​

成员同时也是选项(构造函数的第二个参数)。它们都不是必填的,其中前几个有默认值。

key: (params) => string​

序列化参数,用于在全局 store 中构建查找键。

默认值:

`${this.name} ${JSON.stringify(params)}`;

不选择数据的值(例如 AbortSignal)请作为成员传入,而不是作为参数。

覆盖

覆盖 key 时,如果你打算使用 testKey 方法,务必同时提供一个相应更新的版本。

testKey(key): boolean​

如果提供的(fetch)key 与此 endpoint 匹配,则返回 true。

它用于配合 <MockResolver /> 使用的模拟 interceptor

name: string​

在 key 中用于区分不同的 endpoint。应当全局唯一。

默认为 this.fetch.name

注意

在会更改函数名的生产构建中,这可能会失效。这通常被称为函数名混淆(mangling)。

这种情况下,你可以覆盖 name,或禁用函数名混淆。

signal?: AbortSignal​

取消该 fetch。在 fetch 函数中以 this.signal 读取它并继续传递,例如 fetch(url, { signal: this.signal })。用 extend() 为单次调用设置它,或者用 useCancelling() 在每次参数变化时中止。参见取消。

sideEffect: boolean​

用于表示该 endpoint 可能有副作用(非幂等)。这会禁止它与 useSuspense() 或 useFetch() 一起使用,因为它们请求该 endpoint 的次数不可预测。

schema: Schema​

以声明式的方式定义如何处理响应

不提供此选项意味着不会提取任何 Entity。

import { Endpoint, Entity } from '@data-client/endpoint';

class User extends Entity {
id = '';
username = '';
}

const getUser = new Endpoint(
({ id }) => fetch(`/users/${id}`),
{ schema: User }
);

dataExpiryLength?: number​

为所获取资源自定义的数据缓存有效期。会覆盖 NetworkManager 中设置的值。

进一步了解过期时间

errorExpiryLength?: number​

为所获取资源自定义的错误有效期。会覆盖 NetworkManager 中设置的值。

errorPolicy?: (error: any) => 'soft' | undefined​

'soft' 会在出错时使用过时数据(如果存在);返回 undefined 或不提供该选项时,结果将是错误。

进一步了解 errorPolicy

errorPolicy(error) {
return error.status >= 500 ? 'soft' : undefined;
}

invalidIfStale: boolean​

表示过时数据应被视为不可用,因此不会从缓存中返回。这意味着即使数据已经存在于缓存中,只要它过时了,useSuspense() 就会挂起。

pollFrequency: number​

轮询频率,单位为毫秒。需要配合 useSubscription() 或 useLive() 使用才会生效。

getOptimisticResponse: (snap, ...args) => expectedResponse​

提供该函数后,使用此 endpoint 的任何获取都会表现得如同该函数返回的 expectedResponse 是一次成功的网络响应。当实际请求完成时(无论失败还是成功),乐观更新都会被实际的网络响应替换。

expectedResponse 会用 endpoint 的 schema 进行规范化,因此 TypeScript 会像检查 Controller.set() 的值一样检查它:Entity 接受其任意字段,而 Collection 接受由这些字段组成的列表。当 endpoint 解析为某个特定类型(例如 process() 的返回值)时,它必须改为匹配该类型。

import { resource } from '@data-client/rest';
import { Post } from './Post';

export { Post };

export const PostResource = resource({
  path: '/posts/:id',
  searchParams: {} as { userId?: string | number } | undefined,
  schema: Post,
}).extend('vote', {
  path: '/posts/:id/vote',
  method: 'POST',
  body: undefined,
  schema: Post,
  getOptimisticResponse(snapshot, { id }) {
    const post = snapshot.get(Post, { id });
    if (!post) throw snapshot.abort;
    return {
      id,
      votes: post.votes + 1,
    };
  },
});
实时预览

expectedResponse 中的 Entity 只需要包含它的主键和发生变化的字段:省略的字段会保留其缓存值。没有主键时,缓存中的 entity 不会改变,因此 UI 会等待服务器(开发构建会记录原因)。当 endpoint 的参数不包含该键时(比如 PATCH /users/profile),可以从 snapshot 中读取它:

const getMe = new RestEndpoint({ path: '/users/me', schema: User });
const updateProfile = new RestEndpoint({
path: '/users/profile',
method: 'PATCH',
body: {} as { firstName: string; bio: string },
schema: User,
getOptimisticResponse(snap, body) {
const { data: user } = snap.getResponse(getMe);
if (!user) throw snap.abort;
return { id: user.id, ...body };
},
});

当 entity 尚未被缓存时,throw snap.abort 会跳过乐观更新。

乐观更新指南

update()​

(normalizedResponseOfThis, ...args) =>
({ [endpointKey]: (normalizedResponseOfEndpointToUpdate) => updatedNormalizedResponse) })
提示

试试改用 Collections。

它们更易用,也更健壮!

UpdateType.ts
type UpdateFunction<
Source extends EndpointInterface,
Updaters extends Record<string, any> = Record<string, any>,
> = (
source: ResultEntry<Source>,
...args: Parameters<Source>
) => { [K in keyof Updaters]: (result: Updaters[K]) => Updaters[K] };

最简单的情况:

userEndpoint.ts
const createUser = new RestEndpoint({
path: '/user',
method: 'POST',
schema: User,
update: (newUserId: string) => ({
[userList.key()]: (users = []) => [newUserId, ...users],
}),
});

更多更新:

Component.tsx
const allusers = useSuspense(userList);
const adminUsers = useSuspense(userList, { admin: true });

下面的 endpoint 确保新用户会立即出现在上述用法中。

userEndpoint.ts
const createUser = new RestEndpoint({
path: '/user',
method: 'POST',
schema: User,
update: (newUserId, newUser) => {
const updates = {
[userList.key()]: (users = []) => [newUserId, ...users],
];
if (newUser.isAdmin) {
updates[userList.key({ admin: true })] = (users = []) => [newUserId, ...users];
}
return updates;
},
});

extend(options): Endpoint​

可用于进一步自定义 endpoint 的定义

const getUser = new Endpoint(({ id }) => fetch(`/users/${id}`));


const getUserNormalized = getUser.extend({ schema: User });

除了这些成员之外,还可以传入 fetch 来覆盖获取函数。

示例​

import { Endpoint } from '@data-client/endpoint';

const UserDetail = new Endpoint(
({ id }) => fetch(`/users/${id}`).then(res => res.json())
);
import { useSuspense, useController } from '@data-client/react';
import { UserDetail } from './api/User';
import UserForm from './UserForm';

function UserProfile({ id }: { id: string }) {
const user = useSuspense(UserDetail, { id });
const ctrl = useController();

return <UserForm user={user} onSubmit={() => ctrl.fetch(UserDetail)} />;
}

更多内容​

动机​

以下两者是有区别的:

  • 网络 API 是什么
    • 如何发起请求、预期的响应字段等
  • 它如何被使用
    • 绑定数据、轮询、触发命令式获取等

因此,在这两个概念之间清晰地分离关注点会带来很多好处。

借助 TypeScript Standard Endpoints,我们定义了一套在 TypeScript 中声明网络 API 定义的标准。

  • 让 API 作者可以发布包含其 API 接口的 npm 包
  • 任何支持该标准的库都可以使用这些定义,便于在 Vue、React、Angular 等库之间通用
  • 由于输出非常精简,编写代码生成流程会容易得多
  • 产品开发者可以在行为各异的多种场景中使用这些定义
  • 产品开发者可以轻松地在行为需求不同的平台(如 React Native 和 React Web)之间共享代码

Endpoint 包含什么​

  • 一个用于解析结果的函数
  • 一个用于唯一地存储这些结果的函数
  • 可选:关于如何将数据存储到规范化缓存中的信息
  • 可选:该请求是否可能有副作用——以防止重复调用