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

restii

v0.4.0

Published

Energize your REST API with React hooks and a centralized cache.

Downloads

18

Readme

restii

Energize your REST API 🌿 with React hooks and a centralized cache.

GitHub Workflow Status Code Climate coverage Code Climate maintainability npm bundle size npm type definitions GitHub stars

Features:

  • 🚀 A set of React hooks for querying HTTP API data
  • 💾 Turnkey API response caching
  • 🖇 Parallel request de-duplication
  • 📡 Support for API requests and cache queries outside of React components (in sagas, thunks, etc.)
  • 📥 Parses response bodies of any data type ('json', 'blob', 'text')
  • 💡 Designed with full Typescript support

Contents

  1. Motivation
  2. Basic Usage
  3. Installation & Setup
  4. Guide (wip)
  5. Comparison to similar libraries (wip)
  6. Usage with Redux (wip)
  7. API (wip)

Motivation

At d1g1t, we make over 400 REST API calls in our enterprise investment advisor platform. Over time, as we started using React hooks and wanted to introduce caching optimizations, it was clear that we needed to overhaul our internal REST API fetching library to use patterns that scale with our app.

restii synthesizes patterns from other libraries, such as apollo-client, swp, and react-query. The primary difference is that it's specifically designed for making HTTP calls to your API. It allows you to request API data with URL paths, query parameters, request bodies, and HTTP headers. The caching layer will deterministically map these HTTP request parameters to response bodies, allowing the user to easily query their API and defer caching logic to restii.

Since it works well for d1g1t's purposes, we decided to open-source the library to help others who are building a REST API-consuming React application.

Basic Usage

Query your API (ex. fetching a user's profile):

import React from 'react'
import {useApiQuery} from 'restii'

const MyComponent = (props) => {
  const [userQuery] = useApiQuery({url: `/users/${props.userId}`})

  if (userQuery.error) {
    // display error
  }

  if (userQuery.loading) {
    // display loading state
  }

  return <h1>{userQuery.data.firstName}</h1>
}

As you start adding more API requests, we strongly recommend organizing your request definitions into centralized "endpoint" classes, grouped by domain/resource.

Continuing our example, we'll create a UserEndpoints class to define endpoints under the '/users' base path. We'll subclass restii#HttpEndpoints, which gives us static HTTP helper methods:

import {HttpEndpoints} from 'restii'

export class UserEndpoints extends HttpEndpoints {
  static basePath = '/users'

  static list(query) {
    return super._get('', {query})
    // {method: 'GET', url: '/users?serializedQuery'}
  }

  static create(body) {
    return super._post('', {body})
    // {method: 'POST', url: '/users'}
  }

  static findById(id) {
    return super._get(`/${id}`)
    // {method: 'GET', url: `/users/${id}`}
  }

  static update(id, body) {
    return super._put(`/${id}`, {body})
    // {method: 'PUT', url: `/users/${id}`, body}
  }

  static partialUpdate(id, body) {
    return super._patch(`/${id}`, {body})
    // {method: 'PATCH', url: `/users/${id}`, body}
  }

  static destroy(id) {
    return super._delete(`/${id}`)
    // {method: 'DELETE', url: `/users/${id}`}
  }

  // ad-hoc, custom request:
  static requestPasswordReset(id, resetToken, body) {
    return super._post(`/users/${id}`, {
      body,
      headers: {'x-reset-token': resetToken}
    })
    // {method: 'POST', url: `/users/${id}`, headers: {'x-reset-token': resetToken}, body}
  }
}

If your endpoints follow common REST-ful conventions, you can subclass restii#RestEndpoints (which subclasses restii#HttpEndpoints) to reduce REST boilerplate:

import {RestEndpoints} from 'restii'

export class UserEndpoints extends RestEndpoints {
  static basePath = '/users'

  static list(query) {
    return super._list(query)
  }

  static create(body) {
    return super._create(body)
  }

  static findById(id) {
    return super._findById(id)
  }

  static update(id, body) {
    return super._update(id, body)
  }

  static partialUpdate(id, body) {
    return super._partialUpdate(id, body)
  }

  static destroy(id) {
    return super._destroy(id)
  }

  static requestPasswordReset(id, resetToken, body) {
    return super._post(`/users/${id}`, {
      body,
      headers: {'x-reset-token': resetToken}
    })
  }
}

Then you can use these endpoints to make queries:

import React from 'react'
import {useApiQuery} from 'restii'

import {UserEndpoints} from 'my-app/endpoints'

const MyComponent = (props) => {
  const [usersQuery] = useApiQuery(UserEndpoints.list({limit: 10}))
  const [userQuery] = useApiQuery(UserEndpoints.findById(props.userId))
  // ... etc
}

To make one-off requests (ie. form submissions, deletions, etc), you can use the Api client instance directly:

import React, {useState} from 'react'
import {useApi} from 'restii'

import {UserEndpoints} from 'my-app/endpoints'

const DeleteUser = (props) => {
  const api = useApi()
  const [deleting, setDeleting] = useState(false)

  const handleDelete = async () => {
    setDeleting(true)

    try {
      await api.request(UserEndpoints.destroy(props.userId))
      // navigate to a different page, etc.
    } catch (error) {
      // handle error
    } finally {
      setDeleting(false)
    }
  }

  return (
    <>
      <button type='button' onClick={handleDeleteUser} disabled={deleting}>
        Delete User
      </button>
    </>
  )
}

Installation & Setup

Install the package as a dependency:

npm install --save restii

# or

yarn add restii

Create an Api instance and provide it to your app:

import {Api, ApiProvider} from 'restii'

const api = new Api({
  // ↓ prefixes all request urls
  baseUrl: 'http://your-api.com'
})

const App = () => (
  <ApiProvider api={api}>{/* render your app here */}</ApiProvider>
)

You can now start defining endpoints and making requests in your app.

Guide

Caching

How cache data is keyed

TODO explain how requests are deterministically keyed for caching (without request body)

Using the cache when requesting data

TODO explain how to use fetchPolicy

Writing to the cache directly

TODO

Dependent queries

TODO

Re-fetching a query

TODO

Custom response body parsing

TODO

Custom query string serialization

TODO

Setting default headers (ie. an auth token) for all requests

TODO

Typescript

TODO

Comparison to similar libraries

TODO: add comparisons to react-query/swr, rest-hooks, apollo-graphql (with apollo-link-rest)

Usage with Redux

TODO

API

TODO