Ninja Power Manifesto

    @rest-hooks/rest
    TypeScript icon, indicating that this package has built-in type declarations

    6.3.3 • Public • Published

    Rest Hooks for REST

    CircleCI Coverage Status npm downloads bundle size npm version PRs Welcome Chat

    Extensible CRUD patterns for REST APIs.

    Simple TypeScript definition

    import { Entity, createResource } from '@rest-hooks/rest';
    
    class Article extends Entity {
      id: number | undefined = undefined;
      title = '';
      body = '';
    
      pk() {
        return this.id;
      }
    }
    const ArticleResource = createResource({
      path: '/articles/:id',
      schema: Article,
    });

    Entity defines a data model. createResource creates a collection of six RestEndpoints

    RestEndpoints are functions (and more) that return a Promise. Both call parameters and return value are automatically inferred from the options used to construct them.

    path is a templating language using path-to-regex compile.

    Standard CRUD Endpoints

    Reads

    const article = useSuspense(ArticleResource.get, { id: 5 });
    const articles = useSuspense(ArticleResource.getList);
    const [article, setArticle] = useState();
    useEffect(() => {
      setArticle(await ArticleResource.get({ id: 5 }));
    }, []);

    Mutates

    const ctrl = useController();
    const updateArticle = data => ctrl.fetch(ArticleResource.update, { id }, data);
    const partialUpdateArticle = data =>
      ctrl.fetch(ArticleResource.partialUpdate, { id }, data);
    const createArticle = data => ctrl.fetch(ArticleResource.create, data);
    const deleteArticle = data => ctrl.fetch(ArticleResource.delete, { id });

    Use with Node

    const article = await ArticleResource.get({ id: 5 });
    const articles = await ArticleResource.getList();

    Programmatic queries

    const sortedArticles = new Query(
      new schema.All(Article),
      (entries, { asc } = { asc: false }) => {
        const sorted = [...entries].sort((a, b) => a.title.localeCompare(b.title));
        if (asc) return sorted;
        return sorted.reverse();
      },
    );
    
    const articlesUnsorted = useCache(sortedArticles);
    const articlesAscending = useCache(sortedArticles, { asc: true });
    const articlesDescending = useCache(sortedArticles, { asc: false });

    Prior Art

    Install

    npm i @rest-hooks/rest

    DownloadsWeekly Downloads

    3,876

    Version

    6.3.3

    License

    Apache-2.0

    Unpacked Size

    337 kB

    Total Files

    87

    Last publish

    Collaborators

    • ntucker
    • ljharb