reactive/data-client / .agents/skills/data-client-endpoint-setup
data-client-endpoint-setup
VerifiedSet up @data-client/endpoint for custom async operations. Wraps existing async functions with Endpoint for use with Data Client hooks. Use after data-client-setup detects non-REST/GraphQL async patterns.
| File | Kind | Size |
|---|---|---|
| SKILL.md | skill md | 8.5 KB |
| evals/evals.json | config | 2.2 KB |
| references.json | config | 113 B |
| references/Endpoint.md | markdown | 20.9 KB |
| references/Endpoint.vue.md | markdown | 20.5 KB |
references/Endpoint.md
View on GitHub<!-- Generated by `yarn build:skills` from docs/rest/api/Endpoint.md (react). Edit the source doc, not this file. -->
# Endpoint
`Endpoint` are for any asynchronous function (one that returns a Promise).
`Endpoints` define a strongly typed standard interface of relevant metadata and lifecycles
useful for Reactive Data Client and other stores.
Package: [@data-client/endpoint](https://www.npmjs.com/package/@data-client/endpoint)
> **Tip**
>
> Endpoint is a protocol independent class. Try using the protocol specific patterns
> [REST](https://dataclient.io/rest/api/RestEndpoint), [GraphQL](https://dataclient.io/graphql/api/GQLEndpoint),
> or [getImage](https://dataclient.io/docs/guides/img-media#just-images) instead.
<details>
<summary>Interface</summary>
**Interface**
```typescript
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;
}
```
**Class**
```typescript
class Endpoint<F extends (...args: any) => Promise<any>>
implements EndpointInterface
{
constructor(fetchFunction: F, options: EndpointOptions);
key(...args: Parameters<F>): string;
readonly sideEffect?: true;
readonly schema?: Schema;
fetch: F;
extend(options: EndpointOptions): Endpoint;
}
export interface EndpointOptions extends EndpointExtraOptions {
key?: (params: any) => string;
sideEffect?: true | undefined;
schema?: Schema;
}
```
**EndpointExtraOptions**
```typescript
export interface EndpointExtraOptions<F extends FetchFunction = FetchFunction> {
/** Default data expiry length, will fall back to NetworkManager default if not defined */
readonly dataExpiryLength?: number;
/** Default error expiry length, will fall back to NetworkManager default if not defined */
readonly errorExpiryLength?: number;
/** Poll with at least this frequency in milliseconds */
readonly pollFrequency?: number;
/** Marks cached resources as invalid if they are stale */
readonly invalidIfStale?: boolean;
/** Enables optimistic updates for this request - uses return value as assumed network response */
readonly getOptimisticResponse?: (
snap: SnapshotInterface,
...args: Parameters<F>
) => ResolveType<F>;
/** Determines whether to throw or fallback to */
readonly errorPolicy?: (error: any) => 'soft' | undefined;
/** User-land extra data to send */
readonly extra?: any;
}
```
</details>
## Usage
`Endpoint` makes existing async functions usable in any Reactive Data Client context with full TypeScript enforcement.
```ts title="interface"
export interface Todo {
id: number;
userId: number;
title: string;
completed: boolean;
}
```
```ts title="api" {12}
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);
```
```tsx title="React"
import { useSuspense } from '@data-client/react';
import { getTodo } from './api';
function TodoDetail() {
const todo = useSuspense(getTodo, 1);
return <div>{todo.title}</div>;
}
render(<TodoDetail />);
```
### Configuration sharing
Use [Endpoint.extend()](#extend) instead of `{...getTodo}` (spread)
```ts
const getTodoNormalized = getTodo.extend({ schema: Todo });
const getTodoUpdatingEveryFiveSeconds = getTodo.extend({ pollFrequency: 5000 });
```
### Cancellation and other non-key values {#members-not-args}
The arguments are the [key](#key): they say which data the store holds. Keep values that don't
choose the data, like an [AbortSignal](https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal)
or an SDK client, out of them. As arguments, every hook call would need one, and calls with and
without one get different keys, so they don't share data. Make such a value a member instead, and
read it from `this` in the fetch function. [signal](#signal) is already typed; declare any other
member in the options.
```ts title="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] },
);
```
Set the member for one call with [extend()](#extend), so other calls keep their own.
```ts
// ctrl is the Controller, from useController() or a router loader
const abort = new AbortController();
ctrl.fetch(getPosts.extend({ signal: abort.signal }), { page: 2 });
```
[useCancelling()](https://dataclient.io/docs/api/useCancelling) does this for you, and aborts when the params change:
```tsx title="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} />;
}
```
Limits:
- The request stops only if the fetch function passes the signal on, and the SDK hands it to
`fetch()`.
- Reads (no `sideEffect`) with the same params share one request. A signal only cancels a request
its own call started, and that cancels it for every call sharing it.
- Data Client ignores a rejection named `AbortError`, which is what `fetch()` throws. If your SDK
wraps the abort in another error, rethrow one named `AbortError`; otherwise it is stored as a
failed fetch, and renders with those params throw it until it [expires](#errorexpirylength).
- Aborting a mutation undoes its optimistic update, but the server may already have applied it.
## Lifecycle
### Success
```mermaid
flowchart LR
subgraph Controller.fetch
direction TB
key("Endpoint.key(...args)")--->dispatch("dispatch(FETCH)")
end
subgraph managers
NetworkManager-->endpoint("endpoint(...args)")
endpoint--resolves-->Controller.resolve
Controller.resolve("Controller.resolve(response)")-->dispatchR("dispatch(SET_RESPONSE)")
end
managers--FETCH-->reducer:FETCH
Controller.fetch--FETCH-->managers
subgraph reducer:FETCH
optimistic("Endpoint.?getOptimisticResponse()")-->SET_RESPONSE
subgraph SET_RESPONSE
normalize(normalize)-->update("Endpoint.update()")
end
end
subgraph reducer:SET_RESPONSE
direction LR
normalize2(normalize)-->update2("Endpoint.update()")
end
managers--SET_RESPONSE-->reducer:SET_RESPONSE
click key "/rest/api/Endpoint#key"
click NetworkManager "/docs/api/NetworkManager"
click optimistic "/rest/api/Endpoint#getoptimisticresponse"
click update "/rest/api/Endpoint#update"
click update2 "/rest/api/Endpoint#update"
click dispatch "/docs/api/Actions#fetch"
click dispatchR "/docs/api/Actions#set_response"
```
### Error
```mermaid
flowchart LR
subgraph Controller.fetch
direction TB
key("Endpoint.key(...args)")--->dispatch("dispatch(FETCH)")
end
subgraph managers
NetworkManager-->endpoint("endpoint(...args)")
endpoint--rejects-->Controller.resolve
Controller.resolve("Controller.resolve(error)")-->dispatchR("dispatch(SET_RESPONSE)")
end
managers--FETCH-->reducer:FETCH
Controller.fetch--FETCH-->managers
subgraph reducer:FETCH
optimistic("Endpoint.?getOptimisticResponse()")-->SET_RESPONSE
subgraph SET_RESPONSE
normalize(normalize)-->update("Endpoint.update()")
end
end
subgraph reducer:reduceError
direction LR
filterOptimistic(filterOptimistic)-->errorPolicy("Endpoint.errorPolicy()")
end
managers--SET_RESPONSE:error-->reducer:reduceError
click key "/rest/api/Endpoint#key"
click optimistic "/rest/api/Endpoint#getoptimisticresponse"
click update "/rest/api/Endpoint#update"
click errorPolicy "/rest/api/Endpoint#errorpolicy"
click NetworkManager "/docs/api/NetworkManager"
click dispatch "/docs/api/Actions#fetch"
click dispatchR "/docs/api/Actions#set_response"
```
## Endpoint Members
Members double as options (second constructor arg). While none are required, the first few
have defaults.
### key: (params) => string {#key}
Serializes the parameters. This is used to build a lookup key in global stores.
Default:
```typescript
`${this.name} ${JSON.stringify(params)}`;
```
Pass values that don't choose the data, like an `AbortSignal`, as [members](#members-not-args) rather
than params.
> **Warning: Overrides**
>
> When overriding `key`, be sure to also include an updated [testKey](#testKey) if
> you intend on using that method.
### testKey(key): boolean {#testKey}
Returns `true` if the provided (fetch) [key](#key) matches this endpoint.
This is used for mock interceptors with with [\<MockResolver />](https://dataclient.io/docs/api/MockResolver)
### name: string {#name}
Used in [key](#key) to distinguish endpoints. Should be globally unique.
Defaults to `this.fetch.name`
> **Warning**
>
> This may break in production builds that change function names.
> This is often know as [function name mangling](https://terser.org/docs/api-reference#mangle-options).
>
> In these cases you can override `name` or disable function mangling.
### signal?: AbortSignal {#signal}
Cancels the fetch. Read it as `this.signal` in the fetch function and pass it on, like
`fetch(url, { signal: this.signal })`. Set it for one call with [extend()](#extend), or
abort on each params change with [useCancelling()](https://dataclient.io/docs/api/useCancelling). See
[cancellation](#members-not-args).
### sideEffect: boolean {#sideeffect}
Used to indicate endpoint might have side-effects (non-idempotent). This restricts it
from being used with [useSuspense()](https://dataclient.io/docs/api/useSuspense) or [useFetch()](https://dataclient.io/docs/api/useFetch) as those can hit the
endpoint an unpredictable number of times.
### schema: Schema {#schema}
Declarative definition of how to [process responses](https://dataclient.io/rest/api/schema)
- [where](https://dataclient.io/rest/api/schema) to expect [Entities](https://dataclient.io/rest/api/Entity)
- Functions to [deserialize fields](https://dataclient.io/rest/guides/network-transform#deserializing-fields)
Not providing this option means no entities will be extracted.
```tsx
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 {#dataexpirylength}
Custom data cache lifetime for the fetched resource. Will override the value set in NetworkManager.
[Learn more about expiry time](https://dataclient.io/docs/concepts/expiry-policy#expiry-time)
### errorExpiryLength?: number {#errorexpirylength}
Custom data error lifetime for the fetched resource. Will override the value set in NetworkManager.
### errorPolicy?: (error: any) => 'soft' | undefined {#errorpolicy}
'soft' will use stale data (if exists) in case of error; undefined or not providing option will result
in error.
[Learn more about errorPolicy](https://dataclient.io/docs/concepts/error-policy)
```ts
errorPolicy(error) {
return error.status >= 500 ? 'soft' : undefined;
}
```
### invalidIfStale: boolean {#invalidifstale}
Indicates stale data should be considered unusable and thus not be returned from the cache. This means
that useSuspense() will suspend when data is stale even if it already exists in cache.
### pollFrequency: number {#pollfrequency}
Frequency in millisecond to poll at. Requires using [useSubscription()](https://dataclient.io/docs/api/useSubscription) or
[useLive()](https://dataclient.io/docs/api/useLive) to have an effect.
### getOptimisticResponse: (snap, ...args) => expectedResponse {#getoptimisticresponse}
When provided, any fetches with this endpoint will behave as though the `expectedResponse` return value
from this function was a succesful network response. When the actual fetch completes (regardless
of failure or success), the optimistic update will be replaced with the actual network response.
`expectedResponse` is normalized with the endpoint's [schema](#schema), so TypeScript checks it like a
[Controller.set()](https://dataclient.io/docs/api/Controller#set) value: an [Entity](https://dataclient.io/rest/api/Entity) takes any of its fields, and a
[Collection](https://dataclient.io/rest/api/Collection) takes a list of them. When the endpoint resolves a specific type, like the return
of [process()](https://dataclient.io/rest/api/RestEndpoint#process), it must match that type instead.
```ts title="Post"
import { Entity, EntityMixin } from '@data-client/rest';
export class Post extends Entity {
id = 0;
author = { id: 0 };
title = '';
body = '';
votes = 0;
static key = 'Post';
static schema = {
author: EntityMixin(
class User {
id = 0;
},
),
};
}
```
```ts title="PostResource" {15-22}
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,
};
},
});
```
```tsx title="PostItem" {8}
import { useController } from '@data-client/react';
import NumberFlow from '@number-flow/react';
import { PostResource, type Post } from './PostResource';
export default function PostItem({ post }: Props) {
const ctrl = useController();
const handleVote = () => {
ctrl.fetch(PostResource.vote, { id: post.id });
};
return (
<article className="listItem">
<button
className="upvote"
onClick={handleVote}
aria-label={`Upvote, ${post.votes} votes`}
>
<NumberFlow value={post.votes} />
</button>
<div>
<h4>{post.title}</h4>
<p className="meta">{post.body}</p>
</div>
</article>
);
}
interface Props {
post: Post;
}
```
```tsx title="TotalVotes" {12}
import { Query } from '@data-client/rest';
import { useQuery } from '@data-client/react';
import NumberFlow from '@number-flow/react';
import { PostResource } from './PostResource';
const queryTotalVotes = new Query(
PostResource.getList.schema,
posts => posts.reduce((total, post) => total + post.votes, 0),
);
export default function TotalVotes({ userId }: Props) {
const totalVotes = useQuery(queryTotalVotes, { userId });
if (totalVotes === undefined) return null;
return (
<span className="meta">
<NumberFlow value={totalVotes} /> votes
</span>
);
}
interface Props {
userId: number;
}
```
```tsx title="PostList"
import { useSuspense } from '@data-client/react';
import { PostResource } from './PostResource';
import PostItem from './PostItem';
import TotalVotes from './TotalVotes';
function PostList() {
const userId = 2;
const posts = useSuspense(PostResource.getList, { userId });
return (
<>
<header className="appHeader">
<h1 className="appTitle">Posts</h1>
<TotalVotes userId={userId} />
</header>
<div className="list">
{posts.map(post => (
<PostItem key={post.pk()} post={post} />
))}
</div>
</>
);
}
render(<PostList />);
```
An [Entity](https://dataclient.io/rest/api/Entity) in `expectedResponse` only needs its [primary key](https://dataclient.io/rest/api/Entity#pk) and the fields that
change: fields it leaves out keep their cached values. Without the primary key the cached entity doesn't change,
so the UI waits for the server (development builds log why). When the endpoint's arguments don't include the
key, like `PATCH /users/profile`, read it from the [snapshot](https://dataclient.io/docs/api/Snapshot):
```ts
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 };
},
});
```
`throw snap.abort` skips the optimistic update when the entity isn't cached yet.
[Optimistic update guide](https://dataclient.io/rest/guides/optimistic-updates)
### update() {#update}
```ts
(normalizedResponseOfThis, ...args) =>
({ [endpointKey]: (normalizedResponseOfEndpointToUpdate) => updatedNormalizedResponse) })
```
> **Tip**
>
> Try using [Collections](https://dataclient.io/rest/api/Collection) instead.
>
> They are much easier to use and more robust!
```ts title="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] };
```
Simplest case:
```ts title="userEndpoint.ts"
const createUser = new RestEndpoint({
path: '/user',
method: 'POST',
schema: User,
update: (newUserId: string) => ({
[userList.key()]: (users = []) => [newUserId, ...users],
}),
});
```
More updates:
```typescript title="Component.tsx"
const allusers = useSuspense(userList);
const adminUsers = useSuspense(userList, { admin: true });
```
The endpoint below ensures the new user shows up immediately in the usages above.
```ts title="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 {#extend}
Can be used to further customize the endpoint definition
```typescript
const getUser = new Endpoint(({ id }) => fetch(`/users/${id}`));
const getUserNormalized = getUser.extend({ schema: User });
```
In addition to the members, `fetch` can be sent to override the fetch function.
## Examples
**Basic**
```typescript
import { Endpoint } from '@data-client/endpoint';
const UserDetail = new Endpoint(
({ id }) => fetch(`/users/${id}`).then(res => res.json())
);
```
**With Schema**
```typescript
import { Endpoint, Entity } from '@data-client/endpoint';
class User extends Entity {
id = '';
username = '';
}
const UserDetail = new Endpoint(
({ id }) => fetch(`/users/${id}`).then(res => res.json()),
{ schema: User }
);
```
**List**
```typescript
import { Endpoint, Entity } from '@data-client/endpoint';
class User extends Entity {
id = '';
username = '';
}
const UserList = new Endpoint(
() => fetch(`/users/`).then(res => res.json()),
{ schema: [User] }
);
```
**React**
```tsx
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)} />;
}
```
**JS/Node Schema**
```typescript
const user = await UserDetail({ id: '5' });
console.log(user);
```
### Additional
- [Pagination](https://dataclient.io/rest/guides/pagination)
- [Mocking unfinished endpoints](https://dataclient.io/rest/guides/mocking-unfinished)
- [Optimistic updates](https://dataclient.io/rest/guides/optimistic-updates)
## Motivation
There is a distinction between
- What are networking API is
- How to make a request, expected response fields, etc.
- How it is used
- Binding data, polling, triggering imperative fetch, etc.
Thus, there are many benefits to creating a distinct seperation of concerns between
these two concepts.
With `TypeScript Standard Endpoints`, we define a standard for declaring in
TypeScript the definition of a networking API.
- Allows API authors to publish npm packages containing their API interfaces
- Definitions can be consumed by any supporting library, allowing easy consumption across libraries like Vue, React, Angular
- Writing codegen pipelines becomes much easier as the output is minimal
- Product developers can use the definitions in a multitude of contexts where behaviors vary
- Product developers can easily share code across platforms with distinct behaviors needs like React Native and React Web
### What's in an Endpoint
- A function that resolves the results
- A function to uniquely store those results
- Optional: information about how to store the data in a normalized cache
- Optional: whether the request could have side effects - to prevent repeat calls
Related skills
| Skill | Stars | Updated | Works with | Status | Install |
|---|---|---|---|---|---|
| slack-gif-creatoranthropics/skillsKnowledge and utilities for creating animated GIFs optimized for Slack. Provides constraints, validation tools, and animation concepts. Use when users request animated GIFs for Slack like "make me a GIF of X doing Y for Slack." | Stars: 196k | Updated | Claude CodeCodex | Verified | Install |
| ponytailDietrichGebert/ponytailLazy senior dev mode for any coding task: the smallest change that fully solves it, and a reply a busy human understands in one read. | Stars: 193k | Updated | Claude CodeCodex | Verified | Install |
| ponytail-debtDietrichGebert/ponytailHarvest every shortcut: comment into one debt ledger, so deferrals get tracked instead of forgotten. One-shot report. | Stars: 193k | Updated | Claude CodeCodex | Verified | Install |
| ponytail-debtDietrichGebert/ponytailList every `shortcut:` comment (and older `ponytail:` ones) as a debt ledger. One-shot report, changes nothing. Use for "ponytail debt", "what did ponytail defer", "list the shortcuts", /ponytail-debt. | Stars: 193k | Updated | Claude CodeCodex | Verified | Install |