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

fetch-run

v2.8.3

Published

Fetch middleware for the modern minimalist

Downloads

101

Readme

fetch-run

Fetch middleware for the modern minimalist.

Install

yarn add fetch-run

Usage

import { Api } from 'fetch-run';
import * as uses from 'fetch-run/use';

const api = Api.create('https://example.org/api/v1');

if (__DEV__) {
  api.use(uses.logger);
}

api.use(uses.error);

// Later in app
type LoginRes = { token: string };
type LoginReq = { email: string; password };
type User = { id: number; name: string };

api.post<LoginRes, LoginReq>('login', data);

api.get<User>(`users/${id}`).then((user) => {});

api.search<User[]>('users', { firstName: 'John' }).then((users) => {});

Middlewares

A simple implementation of the middleware pattern. It allows you to modify the Request object before your API call and use the Response object right after receiving the response from the server.

Here are some examples/implementations of the middleware pattern:

A good way to visualize the middleware pattern is to think of the Request/Response lifecycle as an onion. Every middleware added to the stack being a new onion layer on top of the previous one.

Every middleware takes a Request in and must give a Response out.

type Layer = (req: Request) => Promise<Response>;

type Middleware = (next: Layer) => Layer;

// src/http/my-middleware.ts

export const myMiddleware: Middleware =
  (next: Layer) => async (req: Request) => {
    // Before

    const res: Response = await next(req);

    // After

    return res; // Response
  };

Before/after concept

Let's write a simple middleware that remembers an "access token" and sets a "Bearer header" on the next Request once available.

// src/http/access-token.js

let accessToken;

export default (next) => async (req) => {
  //
  // BEFORE
  // Modify/Use Request
  //

  if (accessToken) {
    req.headers.set('Authorization', `Bearer ${accessToken}`);
  }

  const res = await next(req);

  //
  // AFTER
  // Modify/Use Response
  //

  if (res.access_token) {
    accessToken = res.access_token;
  }

  return res;
};

Execution order (LIFO)

Since everything is a middleware, the order of execution is important.

Middlewares are executed in LIFO order ("Last In, First Out").

Everytime you push a new middleware to the stack, it is added as a new onion layer on top of all existing ones.

Example

api.use(A);
api.use(B);

Execution order:

  1. B "Before" logic
  2. A "Before" logic
  3. (actual fetch call)
  4. A "After" logic
  5. B "After" logic

Note: B is the most outer layer of the onion.

Http flavour

The library also exports an Http flavour that does not transform the Response to JSON.

import { Http } from 'fetch-run';

const http = new Http('https://example.org');

http.use(error);

http.get('index.html').then((res: Response) => {
  // https://developer.mozilla.org/en-US/docs/Web/API/Response
  res.blob();
  res.formData();
  res.json();
  res.text();
  // ...
});

API

constructor(baseUrl: string, defaultOptions?: RequestInit)

Creates a new instance of Api or Http.

const api = new Api('', { credentials: 'include' });

const http = new Http('https://example.org', {
  mode: 'no-cors',
  headers: { 'X-Foo': 'Bar' },
});

static create(baseUrl?: string, defaultOptions?: RequestInit)

Alternative & convenient way for creating an instance.

const api = Api.create('', { credentials: 'include' });

const http = Http.create('https://example.org', {
  mode: 'no-cors',
  headers: { 'X-Foo': 'Bar' },
});

Note

Api.create will add the following default headers:

{
  "Accept": "application/json",
  "Content-Type": "application/json"
}

new Api, new Http & Http.create do not.

use(middleware: Middleware)

Adds a middleware to the stack. See Middlewares and Execution order (LIFO) for more information.

type Layer = (req: Request) => Promise<Response>;
type Middleware = (next: Layer) => Layer;

get<Res>(path: string, options?: RequestInit)

Performs a GET request. If you need to pass query parameters to the URL, use search instead.

search<Res>(path: string, query: object, options?: RequestInit)

Performs a GET request with additional query parameters passed in URL.

post<Res, Req extends BodyData>(path: string, data?: Req, options?: RequestInit)

Performs a POST request.

type BodyData = FormData | object | void;

put<Res, Req extends BodyData>(path: string, data?: Req, options?: RequestInit)

Performs a PUT request.

patch<Res, Req extends BodyData>(path: string, data?: Req, options?: RequestInit)

Performs a PATCH request.

delete(path: string, options?: RequestInit)

Performs a DELETE request.

options?: RequestInit

All options are merged with the default options (constructor) and passed down to the Request object.

Included middleware

HTTP Error

  • Catch HTTP responses with error status code (< 200 || >= 300 – a.k.a. response.ok)
  • Create a custom err: HTTPError
  • Set err.code = res.status
  • Set err.message = res.statusText
  • Set err.request = req
  • Set err.response = res
  • Throw HTTPError
import { error } from 'fetch-run/use';

api.use(error);

Later in app:

import { HTTPError } from 'fetch-run';

try {
  api.updateUser(123, { name: 'Tyron' });
} catch (err) {
  if (err instanceof HTTPError) {
    err.response.json(); //...
  } else {
    throw err;
  }
}

Note (order of execution)

All middlewares registered after the error middleware, will not be executed (error middleware throws).

This is why, for example, you need to register the logger middleware first, so it can log req & res before the error is thrown.

HTTP Error (Metro bundler)

The Metro bundler (React Native) fails with ENOENT error when throwing a custom Error:

Error: ENOENT: no such file or directory, open '<app-root>/HTTPError@http:/127.0.0.1:19000/node_modules/expo/AppEntry.bundle?platform=ios&dev=true&hot=false'

This is why we need to throw a "normal" Error and unfortunately not the custom HTTPError itself (yet?).

This prevents the use of instanceof HTTPError + requires to assert the type when using Typescript:

import { HTTPError } from 'fetch-run';

try {
  // ...
} catch (err: Error) {
  // if (err instanceof HTTPError) // Cannot...
  if (err.name === 'HTTPError') {
    // Assert type...
    (err as HTTPError).response.json(); // ...
  }
}

See source code for more details.

import { errorMetro } from 'fetch-run/use';

api.use(errorMetro);

Log requests & responses (DEV)

A simple Request & Response console logger for when you don't need (yet) the full Debug Remote JS capabilities.

import { logger } from 'fetch-run/use';

if (__DEV__) {
  api.use(logger);
}

// Note: To register before `error` middleware (throws)
// api.use(error)

Source code

XSRF-TOKEN cookie (CSRF)

For example when used with Laravel Sanctum.

  • Get XSRF-TOKEN cookie value
  • Set X-XSRF-TOKEN header
import { xsrf } from 'fetch-run/use';

api.use(xsrf);

Source code