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

@truework/gretchen

v0.1.2

Published

Making fetch happen in Typescript.

Downloads

8

Readme

gretchen npm

Making fetch happen in Typescript.

⚠️ This is beta software, and it might not be ready for production use just yet. However, if you'd like to try it out or contribute, we'd love that and we'd love to hear your thoughts.

Features

  • safe: will not throw on non-200 responses
  • precise: allows for typing of both success & error responses
  • resilient: configurable retries & timeout
  • smart: respects Retry-After header
  • small: won't break your bundle

Install

npm i @truework/gretchen --save

Browser Support

gretchen targets all modern browsers. For IE11 support, you'll need to polyfill fetch, Promise, and Object.assign. For Node.js, you'll need fetch and AbortController.

Usage

Basic usage looks a lot like window.fetch:

import { gretch } from "@truework/gretchen";

const request = gretch("/api/user/12");

The request will be made immediately, but to await the response and consume any response data, use any of the standard fetch body interface methods:

const response = await request.json();

gretchen responses are somewhat special. In Typescript terms, they employ a discriminated union to allow you to type and consume both the success and error responses returned by your API.

In a successful response, the object will look something like this:

{
  url: string,
  status: number,
  data: object, // Response body
  error: undefined,
}

And for an error response it will look something like this:

{
  url: string,
  status: number,
  data: undefined,
  error: object, // Response body, or an Error
}

Config

gretchen defaults to GET requests, and sets credentials to same-origin.

To make different types of requests, or edit headers and other request config, pass a config object:

const response = await gretch("/api/user/12", {
  credentials: "include",
  headers: {
    "Tracking-ID": "abcde12345"
  }
}).json();

Configuring requests bodies should look familiar as well:

const response = await gretch("/api/user/12", {
  method: "PATCH",
  body: JSON.stringify({
    email: `[email protected]`
  })
}).json();

For convenience, there’s also a json shorthand. We’ll take care of stringifying the body:

const response = await gretch("/api/user/12", {
  method: "PATCH",
  json: {
    name: "Megan Rapinoe",
    occupation: "President of the United States"
  }
}).json();

Resilience

gretchen will automatically attempt to retry some types of requests if they return certain error codes. Below are the configurable options and their defaults:

  • attempts - a number of retries to attempt before failing. Defaults to 2.
  • codes - an array of number status codes that indicate a retry-able request. Defaults to [ 408, 413, 429 ].
  • methods - an array of strings indicating which request methods should be retry-able. Defaults to [ "GET" ].
  • delay - a number in milliseconds used to exponentially back-off the delay time between requests. Defaults to 6. Example: first delay is 6ms, second 36ms, third 216ms, and so on.

These options can be set using the configuration object:

const response = await gretch("/api/user/12", {
  retry: {
    attempts: 3
  }
}).json();

Timeouts

By default, gretchen will time out requests after 10 seconds and retry them, unless otherwise configured. To configure timeout, pass a value in milliseconds:

const response = await gretch("/api/user/12", {
  timeout: 20000
}).json();

Hooks

gretchen uses the concept of "hooks" to tap into the request lifecycle. Hooks are good for code that needs to run on every request, like adding tracking headers and logging errors.

before

The before hook runs just prior to the request being made. You can even modify the request directly, like to add headers. The before hook is passed the Request object, and the full options object.

const response = await gretch("/api/user/12", {
  hooks: {
    before(request, options) {
      request.headers.set("Tracking-ID", "abcde");
    }
  }
}).json();

after

The after hook has the opportunity to read the gretchen response. It cannot modify it. This is mostly useful for logging.

const response = await gretch("/api/user/12", {
  hooks: {
    after({ url, status, data, error }) {
      sentry.captureMessage(`${url} returned ${status}`);
    }
  }
}).json();

Instances

gretchen also exports a create method that allows you to configure default options. This is useful if you want to attach something like logging to every request made with the returned instance.

import { create } from "@truework/gretchen";

const gretch = create({
  headers: {
    "X-Powered-By": "@truework/gretchen"
  },
  hooks: {
    after({ error }) {
      if (error) sentry.captureException(error);
    }
  }
});

await gretch("/api/user/12").json();

Usage with Typescript

gretchen is written in Typescript and employs a discriminated union to allow you to type and consume both the success and error responses returned by your API.

To do so, pass your data types directly to the gretch call:

type Success = {
  name: string;
  occupation: string;
};

type Error = {
  code: number;
  errors: string[];
};

const response = await gretch<Success, Error>("/api/user/12").json();

Then, you can safely use the responses:

if (response.error) {
  const {
    code, // number
    errors // array of strings
  } = response.error; // typeof Error
} else if (response.data) {
  const {
    name, // string
    occupation // string
  } = response.data; // typeof Success
}

Why?

There are a lot of options out there for requesting data. Most modern fetch implementations, however, rely on throwing errors. For type-safety, we wanted something that would allow us to type the response, no matter what. We also wanted to bake in a few opinions of our own, although the API is flexible enough for most other applications.

Credits

This library was inspired by ky and fetch-retry.

License

MIT License © Truework

cheap movie reference