Skip to main content

TypeScript Standard Endpoints

Endpoints describe an asynchronous API. They hold its runtime behavior and, optionally, its types.

npm install --save @data-client/endpoint
Run in your terminal
interface Todo {
userId: number;
id: number;
title: string;
completed: boolean;
}
interface Params {
id: number;
}

const fetchTodoDetail = ({ id }: Params): Promise<Todo> =>
fetch(`https://jsonplaceholder.typicode.com/todos/${id}`).then(res =>
res.json(),
);

const todoDetail = new Endpoint(fetchTodoDetail);
Example Usage
console.log(await todoDetail({ id: '1' }));
{
"userId": 1,
"id": 1,
"title": "delectus aut autem",
"completed": false
}

The endpoint holds only the network definition, so any component can use it. Each piece of information you add to it, such as TypeScript types, then helps every place that uses it: types catch typos and give autocomplete.

Define the interface once, and use it anywhere. This removes boilerplate and mistakes, and keeps data consistent across the application.

More than just a function​

An Endpoint is also an object, so it can hold more information about the endpoint.

For example, key() serializes the endpoint and its parameters to a unique string. The cache uses it to store responses and to know when parameters changed.

console.log(todoDetail.key({ id: '1' }));
// fetchTodoDetail [{"id":"1"}]

Members​

The optional second argument sets the endpoint's members. Use methods, not arrow functions, so this can read the other members.

const todoDetailWithCustomizedKey = new Endpoint(fetchTodoDetail, {
key({ id }) {
return `${this.endpointIdentifier}/${id}`;
},
endpointIdentifier: 'todoDetail',
});
console.log(todoDetailWithCustomizedKey.key({ id: '1' }));
// todoDetail/1

Endpoint.extend()​

extend() creates a new endpoint that inherits the members of the original, with correct types. Use it to share patterns, such as authentication, across an API.

This example changes the method member:

const fetchTodoDetail = function ({ id }) {
return fetch(`${this.urlBase}/todos/${id}`, { method: this.method }).then(
res => res.json(),
);
};

const todoDetail = new Endpoint(fetchTodoDetail, {
method: 'GET',
urlBase: 'https://jsonplaceholder.typicode.com',
});
const todoCreate = todoDetail.extend({ method: 'POST' });
const todoUpdate = todoDetail.extend({ method: 'PUT' });