Giter VIP home page Giter VIP logo

gretchen's Introduction

gretchen npm

Making fetch happen in TypeScript.

Looking for more info? Check out our blog post.

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 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.

Quick links

Usage

With fetch, you might do something like this:

const request = await fetch("/api/user/12");
const user = await request.json();

With gretchen, it's very similar:

import { gretch } from "gretchen";

const { data: user } = await gretch("/api/user/12").json();

👉 gretchen aims to provide just enough abstraction to provide ease of use without sacrificing flexibility.

Making a request

Using gretchen is very similar to using fetch. It too defaults to GET, and sets the credentials header to same-origin.

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

To parse a response body, simply call any of the standard fetch body interface methods:

const response = await request.json();

The slight diversion from native fetch here is to allow users to do this in one shot:

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

In addition to the body interface methods you're familiar with, there's also a flush() method. This resolves the request without parsing the body (or errors), which results in slight performance gains. This method returns a slightly different response object, see below for more details.

const response = await gretch("/api/user/authenticated").flush();

Options

To make different types of requests or edit headers and other request config, pass a options 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({
    name: "Megan Rapinoe",
    occupation: "President of the United States",
  }),
}).json();

For convenience, there’s also a json shorthand. We’ll take care of stringifying the body and applying the Content-Type header:

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

Retrying requests

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();

Response handling

gretchen's thin abstraction layer returns a specialized structure from a request. In TypeScript terms, it employs a discriminated union for ease of typing. More on that later.

const { url, status, error, data, response } = await gretch(
  "/api/user/12"
).json();

url and status here are what they say they are: properties of the Response returned from the request.

data

If the response returns a body and you elect to parse it i.e. .json(), it will be populated here.

error

And instead of throwing errors gretchen will populate the error prop with any errors that occur or bodyies returned from non-success (4xx) responses.

Examples of error usage:

  • a /login endpoint returns 401 and includes a message for the user
  • an endpoint times out and an HTTPTimeout error is returned
  • an unknown network error occurs during the request

response

gretchen also provides the full response object in case you need it.

Usage with flush

As mentioned above, gretchen also provides a flush() method to resolve a request without parsing the body or errors. This results in a slightly different response object.

const { url, status, response } = await gretch(
  "/api/user/authenticated"
).flush();

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.

Hooks should be defined as an array. That way you can compose multiple hooks per-request, and define and merge default hooks when creating instances.

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 runs after the request has resolved and any body interface methods have been called. It 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 }, options) => {
        sentry.captureMessage(`${url} returned ${status}`);
      },
    ],
  },
}).json();

Creating 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 "gretchen";

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

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

Base URLs

Another common use case for creating a separate instance is to specify a baseURL for all requests. The baseURL will then be resolved against the base URL of the page, allowing support for both absolute and relative baseURL values.

In the example below, assume requests are being made from a page located at https://www.mysite.com.

Functionally, this:

const gretch = create({
  baseURL: "https://www.mysite.com/api",
});

Is equivalent to this:

const gretch = create({
  baseURL: "/api",
});

So this request:

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

Will resolve to https://www.mysite.com/api/user/12.

Note: if a baseURL is specified, URLs will be normalized in order to concatenate them i.e. a leading slash – /user/12 vs user/12 – will not impact how the request is resolved.

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. But most modern fetch implementations 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, fetch-retry, and others.

License

MIT License © Truework


cheap movie reference

gretchen's People

Contributors

estrattonbailey avatar wjohnson-truework avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

gretchen's Issues

Strongly typed request body?

I'm looking for a solution to typing fetch, and Gretchen looked to be a good fit, but it stops short of typing the request body. Any reason?

Retry does not work when using request body

Hi @estrattonbailey,

I have encountered a problem when using the retry option. It works fine as long as I don't use a request body.

I couldn't figure it out, I debugged and it failed silently in handleRetry. Then I cloned the repo and wrapped a code block in a try/catch:

/* handleRetry.ts */

export async function handleRetry(
	request: () => Promise<Response>,
	method: string,
	retryOptions: Partial<RetryOptions>
) {
	let res;
        // Added try/catch heree
	try {
		res = await request();
	} catch (e) {
		console.log(e);
		return;
	}

Now fetch throws the following error:

Failed to execute 'fetch' on 'Window': Cannot construct a Request with a Request object that has already been used

It appears to happen only when a body is attached to the request, without a request body it works fine.

This answer helped me solve the problem: https://stackoverflow.com/a/55980308/3504096

If I clone the request here: https://github.com/truework/gretchen/blob/master/index.ts#L108-L111

... it works, like so:

/* index.ts */
  const fetcher = () =>
    timeout
      ? handleTimeout(fetch(request.clone()), timeout, controller)
      : fetch(request.clone())

I wanted to submit a pull request but was not authorized to do so.

consider alternate handling of empty response bodies

At the moment, we always read the body with text() first, prior to continuing on to user-defined parsing methods. This is to ensure, for example, that .json() isn't called on an empty response. This is somewhat of a server problem as well, but it's definitely something that should be handled by gretchen.

While this isn't the end of the world, users that receive large payloads may notice performance impact due to parsing the body twice as noted here.

A better way to do this could be to check for the Content-Length header and 204 statuses instead. For our internal purposes, Django appears to set Content-Length, so this should work fine.

CC @nickbytes @JEphron

Remove unecessary response cloning

A while back we read the Response.body twice. Once to validate that it exists and once to process to whatever format the user requests i.e. .json().

We removed this in favor of trusting remote sources' headers, and to return 204 if no content.

With that change we no longer need to clone the Response for a fresh body.

Potentially related: I'm making this issue after discovering that this cloning is failing silently in Node 12 LTS. I'm running this inside a Next.js site and exporting statically. Only happens for some endpoints, namely one with a query string. Removing the .clone() appears to fix this issue, but there might be more to it. Might need to dig deeper in the near future.

Unmapped responses?

Hi there! This project sounds promising and thanks for the good work!

I am trying out gretchen with a newly spun-up react project (v16.12.0) and was not able to get any response data.

Environment

  • react: v16.12.0
  • gretchen: v1.1.2

Code Snippet

  useEffect(() => {
    (async() => {
      console.log(await gretch("https://reqres.in/api/products/3").json())
    })();
  })

Result
The network debugger shows there is indeed data return from the mock server but it is not mapped to the response? Tried with fetch and it works fine. Experimented with different versions 1.11.0 and 1.11.1 and it is still the same.

Screenshot 2020-05-26 at 2 40 38 PM

Retry on json fail

Is there a build-in way to retry the request when json parsing fails? Since it still returns code 200 it cannot be done with retry.codes.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.