Snapshot
Snapshot 会传给用于计算状态更新的用户自定义函数。它们让你可以基于当前状态,安全且高效地访问反规范化后的数据。
interface Snapshot {
get(schema, ...args) => DenormalizeNullable<typeof schema> | undefined;
getResponse(endpoint, ...args) => { data, expiryStatus, expiresAt };
getError(endpoint, ...args) => ErrorTypes | undefined;
fetchedAt: number;
abort: Error;
}
提示
使用 Controller.snapshot() 构造一个 snapshot
用法
Post
PostResource
PostItem.vue
TotalVotes.vue
PostList.vue
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, }; }, });
成员
get(schema, ...args)
getResponse(endpoint, ...args)
returns
{
data: DenormalizeNullable<E['schema']>;
expiryStatus: ExpiryStatus;
expiresAt: number;
}
从给定的状态中获取指定 endpoint/args 组合对应的响应(具有全局引用稳定性)。
data
反规范化后的响应数据。保证所有成员都具有全局引用稳定性。
expiryStatus
export enum ExpiryStatus {
Invalid = 1,
InvalidIfStale,
Valid,
}
Vue 组件只会在挂载时挂起;已挂载的组件在重新获取数据期间会继续显示原有数据。
Valid
- 永远不会挂起。
- 数据过时时可能会获取
InvalidIfStale
- 数据过时时会挂起。
- 数据过时时可能会获取
Invalid
- 总是会挂起
- 总是会获取
expiresAt
表示过期时间的数字。可与 Date.now() 进行比较。
getError(endpoint, ...args)
获取指定 endpoint 的错误(如果有)。没有错误时返回 undefined。
fetchedAt
产生此 snapshot 的那次 fetch 被调用的时间。
abort
这是一个 Error,在 Endpoint.getOptimisticResponse() 中抛出它即可取消乐观更新。