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

@gladknee/fetchy

v1.1.10

Published

A zero dependency wrapper for fetch that provides type-safe returns and custom error handling

Downloads

8

Readme

fetchy

Fetchy is a zero dependency wrapper for JavaScript's fetch method that automatically throws an error on non 200-300 statuses and accepts TypeScript generics for type-safe returns. It also provides error handling that allows you to easily execute different callbacks for different types of errors.

IMPORTANT: The library currently only handles responses with text or JSON (or no) content types. I'll be adding support for other content types in the future.

Documentation

Quick Start

  1. Install the package with npm i @gladknee/fetchy
  2. Import the default fetchy export from the library.
  3. The fetchy object provides four functions for making requests: get, post, put, delete.
  4. A successful request returns a native Response with an additional data key containing any parsed JSON or text.
import fetchy from "@gladknee/fetchy"

// async await method

async function yourFunction() {
  try {
    const { data } = await fetchy.get("https://server.com/api/endpoint")
  } catch (e: any) {}
}

// Chaining method

fetchy
  .get("https://server.com/api/endpoint")
  .then(({ data }) => {})
  .catch((e: any) => {})

Methods

type FetchyResponse<T> = Response & { data: T }

function get<T = any>(
  url: string,
  options?: Omit<RequestInit, "method">
): Promise<FetchyResponse<T>> {}

function post<T = any>(
  url: string,
  options?: Omit<RequestInit, "method">
): Promise<FetchyResponse<T>> {}

function put<T = any>(
  url: string,
  options?: Omit<RequestInit, "method">
): Promise<FetchyResponse<T>> {}

function delete<T = any>(
  url: string,
  options?: Omit<RequestInit, "method">
): Promise<FetchyResponse<T>> {}

Examples

We have a User type and greetUser() function that accepts a User. We'll create a getUser() function that makes a GET request to fetch the user and pass it to the greetUser function.

type User = { id: number; name: string }

function greetUser(user: User) {
  alert(`Hello ${user.name}`)
}

async function getUser() {
  const { data } = await fetchy.get<User>("https://server.com/api/users/me", {
    headers: { Authorization: "Bearer XXXXXX" },
  })
  return data
}

async function getAndGreetUser() {
  try {
    const user = await getUser()

    greetUser(user)
  } catch (e: any) {
    // handle error
  }
}

Error Handling

Import the handleError function from the library. You can then call this function inside your catch block by passing two required parameters: the error and your error handling callback configuration.

import fetchy, { handleError } from "@gladknee/fetchy"

async function someRequest() {
  try {
    const { data } = await fetchy.get("https://server.com/api")
  } catch (e: any) {
    handleError(e, callbackConfig)
  }
}

Handling status codes

async function getAndGreetUser() {
  try {
    const user = await getUser()

    greetUser(user)
  } catch (e: any) {
    handleError(e, {
      status: {
        401: (e) => {
          /* Do something if 401 response */
        },
        500: (e) => {
          /* Do something if 500 response */
        },
        other: (e) => {
          /* Do something on any other non 200-300 statuses */
        },
        all: (e) => {
          /* Do something on any non 200-300 status */
        },
      },
    })
  }
}

Handling response body

async function getAndGreetUser() {
  try {
    const user = await getUser()

    greetUser(user)
  } catch (e: any) {
    handleError(e, {
      body: {
        fieldName: (e, value) => {
          switch (value) {
            case "SOME_VALUE":
              // Do something if response includes { fieldName: "SOME_VALUE" }
              break
            case "SOME_OTHER_VALUE":
              // Do something if response includes { fieldName: "SOME_OTHER_VALUE "}
              break
            default:
            // Do something if response includes { fieldName: <anything else> }
          }
        },
      },
    })
  }
}

Handling client-side errors

async function getAndGreetUser() {
  try {
    const user = await getUser()

    greetUser(user)
  } catch (e: any) {
    handleError(e, {
      client: {
        fetch: (e) => {
          /* Do something if fetch failed */
        },
        network: (e) => {
          /* Do something if network error */
        },
        abort: (e) => {
          /* Do something if user aborted */
        },
        security: (e) => {
          /* Do something if security error */
        },
        syntax: (e) => {
          /* Do something if syntax error */
        },
        all: (e) => {
          /* Do something if any client-side error */
        },
      },
    })
  }
}

Handling any other uncaught errors

async function getAndGreetUser() {
  try {
    const user = await getUser()

    greetUser(user)
  } catch (e: any) {
    handleError(e, {
      status: {
        401: (e) => {
          /* Do something if 401 response */
        },
      },
      other: (e) => {
        /* Do something if any other error is thrown */
      },
    })
  }
}

Handling all errors

You can also execute a callback on any error. This will be executed along with any other triggered callbacks. So in this example, on a 401 or 409 error, the user is redirected and the error is logged.

async function getAndGreetUser() {
  try {
    const user = await getUser()

    greetUser(user)
  } catch (e: any) {
    handleError(e, {
      status: {
        401: () => redirect("/auth"),
        402: () => redirect("/upgrade"),
      },
      all: (e) => {
        logError(e)
      },
    })
  }
}

Example: Combined error handling

NOTE: If multiple error handling conditions are triggered, each of their callbacks will be executed.

async function getAndGreetUser() {
  try {
    const user = await getUser()

    greetUser(user)
  } catch (e: any) {
    handleError(e, {
      status: {
        401: () => redirect("/auth"),
      },
      body: {
        errorMessage: (e, value) => {
          switch (value) {
            case "USER_NOT_ACTIVE":
              alert("Your account is no longer active.")
              break
            default:
              alert(`Error: ${value}`)
          }
        },
      },
      client: {
        network: () => alert("There was a network error."),
      },
      all: (e) => logError(e),
    })
  }
}

Here's the full type definition of a callback configuration:

type CallbackConfig = {
  status?: {
    [key: number]: (e?: any) => void
    other?: (e?: any) => void
    all?: (e?: any) => void
  }
  body?: {
    [key: string | number]: (e?: any, value?: any) => void
  }
  client?: {
    fetch?: (e?: any) => void
    network?: (e?: any) => void
    abort?: (e?: any) => void
    security?: (e?: any) => void
    syntax?: (e?: any) => void
    all?: (e?: any) => void
  }
  other?: (e?: any) => void
  all?: (e?: any) => void
}

Helpful tips

As you can see in the previous example, combining multiple types of error handling can lead to bulky code. One helpful tip is to separate out your error handling logic into their own object(s) and pass them in to your handleError callbacks.

Example:

const handleStatusErrors = {
  401: () => router.push("/auth/signin"),
  402: () => router.push("/upgrade"),
  500: (e: any?) => logInternalServerError(e),
  // ...etc
}

const handleClientErrors = {
  fetch: () => alert("Please check your internet connection."),
  network: () => alert("We experienced a network error. Please try again."),
}

const handleErrorMessages = (e: any, message: string) => {
  switch (message) {
    case "USER_NOT_FOUND":
      alert("You do not have an account.")
      break
    case "USER_DEACTIVED":
      alert("Your account has been deactivated.")
      break
    default:
      alert(`Error: ${message}`)
  }
}

function logError(e: any) {
  // do something to log any errors
}

const myErrorHandlers = {
  status: handleStatusErrors,
  client: handleClientErrors,
  body: {
    errorMessage: handleErrorMessages,
  },
  all: logError,
}

async function someRequest() {
  try {
    const { data } = await fetchy.get("url")
  } catch (e: any) {
    handleErrors(e, myErrorHandlers)
  }
}

Use with TanStack Query (react-query)

Fetchy works great with Tanstack Query. Below is a popular implementation.

export async function getUser() {
  const { data } = await fetchy.get("https://server.com/api/users/me")
  return data
}

export function SomeComponent() {
  const { data, isError, error } = useQuery({
    queryKey: ["yourkey"],
    queryFn: getUser,
  })

  useEffect(() => {
    if (isError) {
      handleError(error, callbackConfig)
    }
  }, [isError, error])
}