Controller
Controller 提供对 Reactive Data Client store 及其生命周期的类型安全访问。每个 store 有一个 Controller。
Controller 会对反规范化进行记忆化,以保证全局引用相等:未变化的 store 数据无论在哪里读取,都会得到同一个对象。这让渲染和查找保持快速。
Controller 会提供给:
- Manager:作为 Manager.middleware 的第一个参数
- Vue:通过 useController()
- composable 的单元测试:通过
@data-client/vue/test中的renderDataCompose()
class Controller {
/*************** Action Dispatchers ***************/
fetch(endpoint, ...args): ReturnType<E>;
fetchIfStale(endpoint, ...args): Promise<Denormalize<E['schema']>>;
expireAll({ testKey }): Promise<void>;
invalidate(endpoint, ...args): Promise<void>;
invalidateAll({ testKey }): Promise<void>;
resetEntireStore(): Promise<void>;
set(queryable, ...args, value): Promise<void>;
set([Entity], rows): Promise<void>;
setResponse(endpoint, ...args, response): Promise<void>;
setError(endpoint, ...args, error): Promise<void>;
resolve(endpoint, { args, response, fetchedAt, error }): Promise<void>;
subscribe(endpoint, ...args): Promise<void>;
unsubscribe(endpoint, ...args): Promise<void>;
/*************** Data Access ***************/
get(queryable, ...args, state): DenormalizeNullable<typeof queryable> | undefined;
getResponse(endpoint, ...args, state): { data; expiryStatus; expiresAt };
getError(endpoint, ...args, state): ErrorTypes | undefined;
snapshot(state: State<unknown>, fetchedAt?: number): SnapshotInterface;
getState(): State<unknown>;
}
Action 派发方法
fetch(endpoint, ...args)
使用给定的 args 获取该 endpoint。获取完成后,响应或错误会写入缓存。
- Create
- Update
- Delete
<script setup lang="ts">
import { useController } from '@data-client/vue';
import { PostResource } from './PostResource';
const ctrl = useController();
const handleSubmit = (e: Event) =>
ctrl.fetch(
PostResource.getList.push,
new FormData(e.target as HTMLFormElement),
);
</script>
<template>
<form @submit.prevent="handleSubmit"><!-- ... --></form>
</template>
<script setup lang="ts">
import { useController } from '@data-client/vue';
import { PostResource } from './PostResource';
const props = defineProps<{ id: string }>();
const ctrl = useController();
const handleSubmit = (e: Event) =>
ctrl.fetch(
PostResource.update,
{ id: props.id },
new FormData(e.target as HTMLFormElement),
);
</script>
<template>
<form @submit.prevent="handleSubmit"><!-- ... --></form>
</template>
<script setup lang="ts">
import { useController } from '@data-client/vue';
import { useRouter } from 'vue-router';
import { Post, PostResource } from './PostResource';
const props = defineProps<{ post: Post }>();
const ctrl = useController();
const router = useRouter();
const handleDelete = async () => {
await ctrl.fetch(PostResource.delete, { id: props.post.id });
router.push('/');
};
</script>
<template>
<div>
<h3>{{ post.title }}</h3>
<button @click="handleDelete">X</button>
</div>
</template>
fetch 的返回值与传给它的 Endpoint 相同。使用 schema 时,它返回反规范化后的值。
const controller = useController();
const post = await controller.fetch(
PostResource.getList.push,
createPayload,
);
post.title;
post.pk();
Endpoint.sideEffect
sideEffect 会改变 fetch() 的行为:
true
- 在缓存更新被提交之前 resolve。
- 每次调用都会发起新的获取。
- 不 await 时,它会产生未处理的 reject,因为没有组件读取它的错误。请 await 它,或使用 useLoading() 显示错误。
false | undefined
- 在缓存更新被提交之后 resolve。
- 相同的请求会被去重,因此同一时间只有一个在进行中。
- 若要发起一个新的请求,请先中止进行中的那个。
- 不 await 也安全:错误会存储起来,供读取该 endpoint 的组件使用,因此永远不会到达全局的未处理 rejection 处理函数(请改为上报它)。
await仍然会 reject。
fetchIfStale(endpoint, ...args)
仅当数据缺失、过时或无效时才获取,并且总是返回一个代表最近一次获取结果的 Promise。这样在预取时可以避免重复获取仍然新鲜的数据。
| 缓存 | 是否获取 | await 得到 | 不 await |
|---|---|---|---|
| 缺失、过时或无效 | 是,与 fetch() 相同 | 获取到的数据,或以其错误 reject | 错误会被存储;没有未处理的 rejection |
| 新鲜 | 否 | 缓存的数据 | 什么也不会发生 |
| 最近一次获取在 errorExpiryLength 内失败 | 否 | 以该错误 reject,就像 useSuspense() 抛出它一样 | 什么也不会发生 |
因此预取无需 await,也无需捕获错误:读取该 endpoint 的组件会照常显示已存储的错误。未 await 的失败不会到达全局的未处理 rejection 处理函数,所以请用错误上报 Manager 上报获取错误。在结果上链式调用 .then() 会生成一个新的
Promise,所以请以 .catch() 结束这条链。
// start a secondary request without waiting for it
controller.fetchIfStale(CommentResource.getList, { issueId });
// wait for the data; rejects if that fetch fails
const issue = await controller.fetchIfStale(IssueResource.get, { id: issueId });
若想在不获取的情况下检查数据是否已缓存且新鲜,请同步读取 getResponse()。
expireAll({ testKey })
将所有匹配 testKey 的响应的过期状态设为 Stale。
当缓存中有很多组 args 时,可以用它只刷新屏幕上的数据。
<script setup lang="ts">
import { useController } from '@data-client/vue';
import { AccountResource, TradeResource, type Trade } from './resources';
import TradeForm from './TradeForm.vue';
const props = defineProps<{ userId: string }>();
const ctrl = useController();
const handleTrade = async (trade: Trade) => {
await ctrl.fetch(
TradeResource.getList.push,
{ user: props.userId },
trade,
);
ctrl.expireAll(AccountResource.get);
ctrl.expireAll(AccountResource.getList);
};
</script>
<template>
<TradeForm @submit="handleTrade" />
</template>
通常更好的做法是把变更的副作用包含在变更响应中。这样可以降低负载、提升性能,并保持状态一致。
invalidate(endpoint, ...args)
强制使用相同 Endpoint 和参数的 useSuspense 重新获取。已挂载的组件会继续显示当前数据,直到重新获取完成。
<script setup lang="ts">
import { useController, useSuspense } from '@data-client/vue';
import { ArticleResource } from './ArticleResource';
const props = defineProps<{ id: string }>();
const ctrl = useController();
const article = await useSuspense(ArticleResource.get, () => ({
id: props.id,
}));
</script>
<template>
<div>
<h1>{{ article.title }}</h1>
<button @click="ctrl.invalidate(ArticleResource.get, { id })">
Refetch
</button>
</div>
</template>
在失效之后,用新的 key 重新挂载组件;新的实例会因无效数据而挂起。
timeout="0" 让 <Suspense> 在等待时显示 fallback,而不是旧内容。重新挂载会重置组件的本地状态。
<script setup lang="ts">
import { ref } from 'vue';
import { useController } from '@data-client/vue';
import { ArticleResource } from './ArticleResource';
import ArticleName from './ArticleName.vue';
const props = defineProps<{ id: string }>();
const ctrl = useController();
const remountKey = ref(0);
async function reload() {
await ctrl.invalidate(ArticleResource.get, { id: props.id });
remountKey.value++;
}
</script>
<template>
<button @click="reload">Reload</button>
<Suspense timeout="0">
<ArticleName :key="remountKey" :id="id" />
<template #fallback><Loading /></template>
</Suspense>
</template>
使用 schema.Invalidate 可以使所有包含某个 Entity 的 endpoint 失效。
对于 REST,可以试试 Resource.delete。
// deletes MyResource(5)
// this will refetch MyResource.get({id: '5'})
// and remove it from MyResource.getList
controller.setResponse(MyResource.delete, { id: '5' }, { id: '5' });
invalidateAll({ testKey })
使所有匹配 testKey 的 endpoint key 失效。
<script setup lang="ts">
import { useController, useSuspense } from '@data-client/vue';
import { ArticleResource } from './ArticleResource';
const props = defineProps<{ id: string }>();
const ctrl = useController();
const article = await useSuspense(ArticleResource.get, () => ({
id: props.id,
}));
</script>
<template>
<div>
<h1>{{ article.title }}</h1>
<button @click="ctrl.invalidateAll(ArticleResource.get)">
Refetch
</button>
</div>
</template>
下面的代码只让 test.com 域名上的 GET endpoint 失效。其他域名的数据仍保留在缓存中。
const myDomain = 'http://test.com';
const testKey = (key: string) => key.startsWith(`GET ${myDomain}`);
function useLogout() {
const ctrl = useController();
return () => ctrl.invalidateAll({ testKey });
}
遇到 401(未授权)时,也请使用 LogoutManager 清除缓存。
import { createApp } from 'vue';
import {
DataClientPlugin,
LogoutManager,
getDefaultManagers,
} from '@data-client/vue';
import App from './App.vue';
import { unAuth } from '../authentication';
const myDomain = 'http://test.com';
const testKey = (key: string) => key.startsWith(`GET ${myDomain}`);
const managers = () => [
new LogoutManager({
handleLogout(controller) {
// call custom unAuth function we defined
unAuth();
// still reset the store
controller.invalidateAll({ testKey });
},
}),
...getDefaultManagers(),
];
const app = createApp(App);
app.use(DataClientPlugin, { managers });
app.mount('#app');
resetEntireStore()
清除整个 Reactive Data Client 缓存。进行中的获取的响应不会被存储。这些获取会以 ResetError(error.name === 'ResetError')reject,但 sideEffect 获取除外,它们仍会以自身的结果或错误结束。
在用户登出或已认证用户切换时使用它。
<script setup lang="ts">
import { useController, useSuspense } from '@data-client/vue';
import { CurrentUserResource } from './CurrentUserResource';
import { impersonateUser } from './auth';
const USER_NUMBER_ONE: string = '1111';
const user = await useSuspense(CurrentUserResource.get);
const ctrl = useController();
const becomeAdmin = () => {
// Changes the current user
impersonateUser(USER_NUMBER_ONE);
ctrl.resetEntireStore();
};
</script>
<template>
<div>
<h1>{{ user.name }}</h1>
<button @click="becomeAdmin">Be Number One</button>
</div>
</template>
set(queryable, ...args, value)
更新任意 Queryable Schema,或者通过 Array 或 Values schema 一次更新多个 Entity。
ctrl.set(
Todo,
// which Todo to update
{ id: '5' },
// merge this data into the Todo in the store
{ id: '5', title: 'tell me friends how great Data Client is' },
);
value 的类型由 schema 决定:Entity 接收其字段(数字和字符串可以互换),而 Collection 或 All 接收一个行列表。Query
接收其所包裹 schema 的输入,因为 set() 是对该 schema 进行规范化,而不是逆向执行 process()。
ctrl.set(TodoResource.getList.schema, [{ id: '5', completed: true }]);
Collection.push 和 unshift 接收该 Collection 的参数(用于选出要添加到的列表),以及一行或一组行。
ctrl.set(TodoResource.getList.schema.push, { userId: '1' }, [
{ id: '6', title: 'Buy milk' },
{ id: '7', title: 'Walk dog' },
]);
当每个成员都把其判别字段声明为字面量(例如 readonly type = 'first')时,
Union 的每一行都会按其选中的成员进行检查,因此 { type: 'first', secondField: 1 } 会报错。只接受已声明的字段,因此被
schemaAttribute 函数读取的键必须在每个成员上声明。
传入一个函数,根据已存储的值推导出新值。这样可以避免竞态条件。
const id = '2';
ctrl.set(Article, { id }, article => ({ id, votes: article.votes + 1 }));
set([Entity], rows)
传入一个 Array schema([Todo] 或 new schema.Array(Todo))和一个行列表,即可在一次 store 更新中更新多个 Entity。每一行都会与已存储的对应 Entity 合并;不在列表中的 Entity 保持不变。
ctrl.set(
[Todo],
[
{ id: '5', completed: true },
{ id: '6', completed: false },
],
);
行的类型由 Entity 的字段决定;数字和字符串可以互换,而对象、数组和 Date 值不会被检查,因为行是原始输入。
对于混合了多种 Entity 类型的列表,请使用 Union;每一行会按其 type 存储:
const Feed = new schema.Union({ post: Post, comment: Comment }, 'type');
ctrl.set(
[Feed],
[
{ id: '1', type: 'post', title: 'Hello' },
{ id: '7', type: 'comment', body: 'Nice!' },
],
);
要一次删除多个 Entity,请使用 Invalidate;每一行只需包含其 pk 字段:
ctrl.set([new schema.Invalidate(Todo)], [{ id: '5' }, { id: '6' }]);
要删除单个 Entity,传入 Invalidate schema 及其对应的行:
ctrl.set(new schema.Invalidate(Todo), { id: '5' });
Values schema 则接收一个由行组成的对象:
ctrl.set(new schema.Values(Todo), {
'5': { id: '5', completed: true },
'6': { id: '6', completed: false },
});
Array、Values 和 Invalidate schema 不接受 args(因此 Entity.pk() 和 Entity.process()
收到的是 []),也不接受更新函数。pk 相同的行会按列表顺序合并,不会经过
Entity.shouldReorder()。请用它来代替逐行调用 set(),例如在批量处理高频数据流更新时。
setResponse(endpoint, ...args, response)
把 response 存入给定 Endpoint 和参数对应的缓存中。
正在为这个 Endpoint 和 args 挂起的组件会 resolve。该 Endpoint 和 args 已有的数据会被更新;entity 会与其已存储的字段合并。
const ctrl = useController();
let websocket: WebSocket;
onMounted(() => {
websocket = new WebSocket(url);
websocket.onmessage = event =>
ctrl.setResponse(
EndpointLookup[event.endpoint],
...event.args,
event.data,
);
});
onUnmounted(() => websocket.close());
这是在 Vue 中的概念验证。基于 Manager 的 websocket 实现更加健壮。
setError(endpoint, ...args, error)
将 error 存储为该 Endpoint 和 args 的结果。
resolve(endpoint, { args, response, fetchedAt, error })
resolve 某次特定的获取,并把 response 存入缓存。
与 setResponse 类似,但 fetchedAt 会把响应绑定到某一次获取,从而移除那次获取的乐观更新。
NetworkManager 会使用它。在 Manager 处理获取请求时使用它。
把获取 action 的 action.meta.fetchedAt 作为 fetchedAt 传入。这样 store 会丢弃在
resetEntireStore() 之前发起的获取的响应,旧的响应也不会让同一个键上更新的获取完成。
subscribe(endpoint, ...args)
为该 Endpoint 和 args 添加一个订阅。每次调用都会让它的订阅者计数加一。
useSubscription 和 useLive 会在挂载时调用它。
自定义 composable 可以调用它,根据其他条件进行订阅。
const controller = useController();
// args can be a ref, computed or getter; this re-runs when it changes
watchEffect(onCleanup => {
const currentArgs = toValue(args);
controller.subscribe(endpoint, ...currentArgs);
onCleanup(() => controller.unsubscribe(endpoint, ...currentArgs));
});
unsubscribe(endpoint, ...args)
移除该 Endpoint 和 args 的一个订阅。每次调用都会让它的订阅者计数减一;计数为 0 时,自动更新停止。
useSubscription 和 useLive 会在卸载时调用它。
数据访问
get(schema, ...args, state)
在 state 中查找任意 Queryable Schema。
Example
useQuery 基于它构建,Manager 也可以用它安全地读取 store。
在组件中,useQuery() 会让结果保持响应式。事件处理函数读取它的当前值:
const props = defineProps<{ id: string }>();
const ctrl = useController();
const todo = useQuery(Todo, () => ({ id: props.id }));
const toggle = () => {
if (!todo.value) return;
ctrl.set(
Todo,
{ id: props.id },
{ id: props.id, completed: !todo.value.completed },
);
};
getResponse(endpoint, ...args, state)
{
data: DenormalizeNullable<E['schema']>;
expiryStatus: ExpiryStatus;
expiresAt: number;
}
从给定的 state 中获取某个 endpoint 和 args 的响应。
data
反规范化后的响应。只要数据未变化,每个成员都保持同一个引用。
expiryStatus
export enum ExpiryStatus {
Invalid = 1,
InvalidIfStale,
Valid,
}
Valid
- 永远不会挂起。
- 数据过时时可能会获取
InvalidIfStale
- 数据过时时会挂起。
- 数据过时时可能会获取
Invalid
- 总是会挂起(仅在 setup 期间;已挂载的组件会保留当前数据,直到重新获取完成)
- 总是会获取
expiresAt
数据过期的时间戳。可与 Date.now() 比较。
Example
useCache 和 useSuspense 基于它构建。Manager 可以用它在给定的 state 中查找响应。
在组件中,useCache() 和 useSuspense() 会让结果保持响应式。事件处理函数读取它们的当前值。
import {
type Manager,
type Middleware,
actionTypes,
} from '@data-client/vue';
export default class MyManager implements Manager {
declare protected websocket: WebSocket;
middleware: Middleware = controller => {
return next => async action => {
if (action.type === actionTypes.FETCH) {
console.log('The existing response of the requested fetch');
console.log(
controller.getResponse(
action.endpoint,
...action.args,
controller.getState(),
).data,
);
}
next(action);
};
};
cleanup() {
this.websocket.close();
}
}
getError(endpoint, ...args, state)
获取某个 endpoint 和 args 的错误,没有错误时返回 undefined。
snapshot(state, fetchedAt)
返回一个 Snapshot。
getState()
获取 Reactive Data Client 中已经提交的内部状态。
只在组件之外使用它:在 Manager 中,或在路由 loader 之类的代码中。
在 computed() 或模板中使用 getState(),store 变化时不会更新。在这些地方请改用
useQuery() 或 useCache()。
要根据变更的结果做后续操作,请使用 fetch() resolve 的值,而不是 getState()。变更会在 store 更新之前 resolve,所以 getState() 中还没有它的响应。
resolve 的值是反规范化后的响应。
<script setup lang="ts">
import { useController } from '@data-client/vue';
import { useRouter } from 'vue-router';
import { PostResource } from './PostResource';
const props = defineProps<{ id: string }>();
const ctrl = useController();
const router = useRouter();
const handleSubmit = async (e: Event) => {
const post = await ctrl.fetch(
PostResource.update,
{ id: props.id },
new FormData(e.target as HTMLFormElement),
);
router.push(`/posts/${post.id}`);
};
</script>
<template>
<form @submit.prevent="handleSubmit"><!-- ... --></form>
</template>