npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@data-client/endpoint

v0.14.16

Published

Declarative Network Interface Definitions

Downloads

4,388

Readme

TypeScript Standard Endpoints

CircleCI Coverage Status npm downloads bundle size npm version PRs Welcome

Declarative, strongly typed, reusable network definitions for networking libraries.

📖Read The Docs

Usage

1) Take any class and async functions

export class Todo {
  id = 0;
  userId = 0;
  title = '';
  completed = false;
}

export const getTodo = (id: string) =>
  fetch(`https://jsonplaceholder.typicode.com/todos/${id}`).then(res => res.json());

export const getTodoList = () =>
  fetch('https://jsonplaceholder.typicode.com/todos').then(res => res.json());

export const updateTodo = (id: string, body: Partial<Todo>) =>
  fetch(`https://jsonplaceholder.typicode.com/todos/${id}`, {
    method: 'PUT',
    body: JSON.stringify(body),
  }).then(res => res.json());

2) Turn them into Resources

import { EntityMixin, Endpoint } from '@data-client/endpoint';
import { Todo, getTodoList, updateTodo } from './existing';

export const TodoEntity = EntityMixin(Todo, { key: 'Todo' });

export const TodoResource = {
  get: new Endpoint(getTodo, {
    schema: TodoEntity,
  }),
  getList: new Endpoint(getTodoList, {
    schema: [TodoEntity],
  }),
  update: new Endpoint(updateTodo, {
    schema: TodoEntity,
    sideEffect: true,
  }),
};

3) Reuse with different hooks

import { useSuspense, useController } from '@data-client/react';

function TodoEdit() {
  const todo = useSuspense(TodoResource.get, '5');
  const ctrl = useController();
  const updateTodo = (data) => ctrl.fetch(TodoResource.update, id, data);

  return <TodoForm todo={todo} onSubmit={updateTodo} />
}

4) Or call directly in node

const todo = await TodoResource.get('5')
console.log(todo);

Why

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

API

@data-client/endpoint defines a standard interface

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

as well as a helper class to make construction easier.

class Endpoint<F extends () => Promise<any>> {
  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;
}

EndpointOptions

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

Disallows usage in hooks like useSuspense() since they might call fetch an unpredictable number of times. Use this for APIs with mutation side-effects like update, create, deletes.

Defaults to undefined meaning no side effects.

schema: Schema

Declarative definition of where Entities appear in the fetch response.

Not providing this option means no entities will be extracted.

import { Entity } from '@data-client/normalizr';
import { Endpoint } from '@data-client/endpoint';

class User extends Entity {
  id = '';
  username = '';
}

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

Endpoint

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 });

API

Networking definition: Endpoints