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

simple-typed-fetch

v0.2.13

Published

Making HTTP requests human way

Downloads

5,247

Readme

Simple Typed Fetch

This package provides utility functions for making HTTP requests with validation using the zod schema validation library. It handles various error cases, client and server errors, and offers an additional simpleFetch wrapper function for easier usage.

To install the required dependencies for this package, run:

npm install simple-typed-fetch

Usage

fetchWithValidation

The fetchWithValidation function is an async function that takes the following parameters:

  • url (string): The URL to fetch data from.
  • schema (Schema): The zod schema for validating the response data.
  • options (RequestInit, optional): Optional fetch options (like method, headers, etc.).
  • errorSchema (Schema, optional): The zod schema for validating error responses (4xx status codes). The function returns a Result object from the neverthrow library, which can be either an Ok or an Err variant. If the response is successfully validated, the function returns an Ok variant with the validated data. In case of an error, it returns an Err variant with error details.

simpleFetch

The simpleFetch function is a higher-order function that wraps the fetchWithValidation function and automatically throws an error in case of an Err result. This function is useful when you prefer working with exceptions rather than Result objects.

Error Handling

This package uses the neverthrow library for error handling. It provides a detailed error object in case of an error, containing the following properties:

  • type (string): A string describing the error type.
  • url (string): The URL where the error occurred.
  • message (string): A human-readable error message.
  • status (number, optional): The HTTP status code of the response (for 4xx and 5xx status codes).
  • error (Error, optional): The original error object (for some error cases).
  • text (string, optional): The response text (for some error cases).

Examples

Here's an example of how to use the fetchWithValidation function with a zod schema:

import { z } from "zod";
import { fetchWithValidation } from "simple-typed-fetch";

const userSchema = z.object({
  id: z.number(),
  name: z.string(),
});

async function fetchUser(userId: number) {
  const result = await fetchWithValidation(
    `https://api.example.com/users/${userId}`,
    userSchema
  );

  if (result.isErr()) {
    console.error("Error fetching user:", result.error.message);
    return;
  }

  console.log("Fetched user:", result.value);
}

And here's an example of how to use the simpleFetch function:

import { z } from "zod";
import { simpleFetch } from "simple-typed-fetch";

const userSchema = z.object({
  id: z.number(),
  name: z.string(),
});

const fetchUser = simpleFetch(async (userId: number) =>
  fetchWithValidation(`https://api.example.com/users/${userId}`, userSchema)
);

(async () => {
  try {
    const user = await fetchUser(1);
    console.log("Fetched user:", user);
  } catch (error) {
    console.error("Error fetching user:", error.message);
  }
})();