Skip to main content
Version: 5.0

Endpoint

Endpoint defines a standard interface that describes the nature of an networking endpoint. It is both strongly typed, and encapsulates runtime-relevant information.

interface EndpointInterface extends EndpointExtraOptions {
(params?: any, body?: any): Promise<any>;
key(parmas?: any): string;
schema?: Readonly<S>;
sideEffects?: true;
// other optionals like 'optimistic'
}

Package: @rest-hooks/endpoint

Endpoint Members

Members double as options (second constructor arg). While none are required, the first few have defaults.

key: (params) => string

Serializes the parameters. This is used to build a lookup key in global stores.

Default:

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

sideEffect: true | undefined

Used to indicate endpoint might have side-effects (non-idempotent). This restricts it from being used with useResource() or useRetrieve() as those can hit the endpoint an unpredictable number of times.

schema: Schema

Declarative definition of how to process responses

Not providing this option means no entities will be extracted.

import { Entity } from '@rest-hooks/normalizr';
import { Endpoint } from '@rest-hooks/endpoint';

class User extends Entity {
readonly id: string = '';
readonly username: string = '';

pk() { return this.id;}
}

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

extend(EndpointOptions): Endpoint

Can be used to further customize the endpoint definition

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


const UserDetailNormalized = UserDetail.extend({ schema: User });

In addition to the members, fetch can be sent to override the fetch function.

EndpointExtraOptions

dataExpiryLength?: number

Custom data cache lifetime for the fetched resource. Will override the value set in NetworkManager.

errorExpiryLength?: number

Custom data error lifetime for the fetched resource. Will override the value set in NetworkManager.

pollFrequency: number

Frequency in millisecond to poll at. Requires using useSubscription() to have an effect.

invalidIfStale: boolean

Indicates stale data should be considered unusable and thus not be returned from the cache. This means that useResource() will suspend when data is stale even if it already exists in cache.

optimisticUpdate: (params, body) => fakePayload

When provided, any fetches with this endpoint will behave as though the fakePayload 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.

update(normalizedResponseOfThis) => ({ [endpointKey]: (normalizedResponseOfEndpointToUpdate) => updatedNormalizedResponse) })

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:

userEndpoint.ts
const createUser = new Endpoint(postToUserFunction, {
schema: User,
update: (newUserId: string) => ({
[userList.key()]: (users = []) => [newUserId, ...users],
}),
});

More updates:

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

The endpoint below ensures the new user shows up immediately in the usages above.

userEndpoint.ts
const createUser = new Endpoint(postToUserFunction, {
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;
},
});

This is usage with a Resource

TodoResource.ts
import { Resource } from '@rest-hooks/rest';

export default class TodoResource extends Resource {
readonly id: number = 0;
readonly userId: number = 0;
readonly title: string = '';
readonly completed: boolean = false;

pk() {
return `${this.id}`;
}

static urlRoot = 'https://jsonplaceholder.typicode.com/todos';

static create<T extends typeof Resource>(this: T) {
const todoList = this.list();
return super.create().extend({
schema: this,
update: (newResourceId: string) => ({
[todoList.key({})]: (resourceIds: string[] = []) => [
...resourceIds,
newResourceId,
],
}),
});
}
}

Examples

import { Endpoint } from '@rest-hooks/endpoint';

const UserDetail = new Endpoint(
({ id })fetch(`/users/${id}`).then(res => res.json())
);
function UserProfile() {
const user = useResource(UserDetail, { id });
const updateUser = useFetcher(UserDetail);

return <UserForm user={user} onSubmit={updateUser} />;
}

Additional

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

See also