Snapshot
Snapshots passed to user-defined function that are used to compute state updates. These allow safe and performant access to the denormalized data based on the current state.
interface Snapshot {
get(schema, ...args) => DenormalizeNullable<typeof schema> | undefined;
getResponse(endpoint, ...args) => { data, expiryStatus, expiresAt };
getError(endpoint, ...args) => ErrorTypes | undefined;
fetchedAt: number;
abort: Error;
}
Use Controller.snapshot() to construct a snapshot
Usage
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, }; }, });
Members
get(schema, ...args)
Looks up any Queryable Schema.
getResponse(endpoint, ...args)
{
data: EndpointDataNullable<E>;
expiryStatus: ExpiryStatus;
expiresAt: number;
}
Gets the (globally referentially stable) response for a given endpoint/args pair from state given.
data
The denormalize response data. Guarantees global referential stability for all members. Its type is EndpointDataNullable.
expiryStatus
export enum ExpiryStatus {
Invalid = 1,
InvalidIfStale,
Valid,
}
Valid
- Will never suspend.
- Might fetch if data is stale
InvalidIfStale
- Will suspend if data is stale.
- Might fetch if data is stale
Invalid
- Will always suspend
- Will always fetch
expiresAt
A number representing time when it expires. Compare to Date.now().
getError(endpoint, ...args)
Gets the error, if any, for a given endpoint. Returns undefined for no errors.
fetchedAt
When the fetch was called that resulted in this snapshot, in milliseconds like Date.now(). Fetches started in the
same millisecond get times a fraction of a millisecond apart, so they keep their order.
abort
This is an Error to be thrown in Endpoint.getOptimisticResponse() to cancel an optimistic update.