1.3.0 • Published 3 years ago

@glenstack/cf-workers-fetch-helpers v1.3.0

Weekly downloads
14
License
MIT
Repository
github
Last release
3 years ago

Cloudflare Workers Fetch Helpers

A collection of chainable helpers to adapt the Fetch API.

Installation

npm install --save @glenstack/cf-workers-fetch-helpers

Usage

All methods exported from this library can be chained together and have the following usage:

import {
  fetchHelper,
  otherFetchHelper,
} from "@glenstack/cf-workers-fetch-helpers";

const fetch1 = fetchHelper(fetch, fetchHelperOptions); // `fetch` is the built-in fetch global
const fetch2 = otherFetchHelper(fetch1, otherFetchHelperOptions); // NOTE: `fetch1` is being chained here, such that `fetch2(request)` calls `fetch1(request)`, which calls `fetch(request)`

(async () => {
  const response = await fetch2("https://example.com");
})();

Where:

  • fetch, fetch1 and fetch2 are all Fetch compatible functions,
  • fetchHelper and otherFetchHelper are fictional functions in this library (see below for the real ones),
  • fetchHelperOptions and otherFetchHelperOptions are the options for these fictional helper functions (again, the real functions and their options follow).

alterURL

Changes the Request URL.

Options Signature

type options =
  | {
      prepend?: string;
      append?: string;
    }
  | {
      mutate: (prevURL: string) => string;
    };

Options

OptionNotes
prependPrepends the URL with a given string.
appendAppends the URL with a given string.
mutateA function that, when given a URL, returns the new URL.

Example Usage

import { alterURL } from "@glenstack/cf-workers-fetch-helpers";

const gitHubFetch = alterURL(fetch, { prepend: "https://api.github.com" });

(async () => {
  const response = await gitHubFetch("/meta");
})();

proxyHost

Replaces the host of a Request URL.

Options Signature

type options = {
  host: string;
};

Options

OptionNotes
hostThe new host to replace in the Request URL.

Example Usage

import { proxyHost } from "@glenstack/cf-workers-fetch-helpers";

const proxiedFetch = proxyHost(fetch, { host: "about.gitlab.com" })(
  async () => {
    const response = await proxiedFetch("https://github.com/pricing");
  }
)();

addHeaders

Adds headers to the Request.

Options Signature

type options = {
  headers: RequestInit["headers"];
};

Options

OptionNotes
headersA Headers object, an object literal, or an array of two-item arrays to set request’s headers.

Example Usage

import { addHeaders } from "@glenstack/cf-workers-fetch-helpers";

const gitHubFetch = addHeaders(fetch, {
  headers: { Authorization: "Basic xyz", "User-Agent": "Awesome-Octocat-App" },
});

(async () => {
  const response = await gitHubFetch("/meta");
})();

authorization

Adds an Authorization header. The following types of authorization are supported:

  • Basic
  • Bearer

Options Signature

type options =
  | {
      username?: string;
      password?: string;
    }
  | {
      bearere: string;
    };

Options

OptionNotes
usernameUsed in basic authorization.
passwordUsed in basic authorization.
bearerA bearer token used in bearer authorization.

Example Usage

import { authorization } from "@glenstack/cf-workers-fetch-helpers";

const gitHubFetch = authorization(fetch, { bearer: "aToken" });

(async () => {
  const response = await gitHubFetch("/meta");
})();

oauth2

A OAuth2 client which automatically refreshes tokens.

Options Signature

type options = {
  tokenRefreshed?: (options: {
    accessToken?: string;
    refreshToken: string;
  }) => Promise<void>;
  accessToken?: string;
  authorizationHasExpired?: (response: Response) => Promise<boolean>;
  refreshToken: string;
  tokenEndpoint: string;
  clientID: string;
  clientSecret: string;
  redirectURI?: string;
  scope?: string;
  refreshFetch?: typeof fetch;
};

Options

OptionNotes
tokenRefreshedA function called when a new token is generated. Useful if you wish to persist the latest valid tokens.
accessTokenAn Access Token.
authorizationHasExpiredA function to evaluate if, given a Response, the Access Token is now invalid. Defaults to returning true if the Response status code is 401.
refreshTokenA valid Refresh Token.
tokenEndpointThe URL of the authorization server which refreshes tokens.
clientIDThe application client ID.
clientSecretThe application client secret.
redirectURIAlthough not in the specification, some authorization servers require a valid redirect URI when refreshing tokens.
scopeThe scope of the access token.
refreshFetchThe fetch function to use when making calls to the authorization server. Defaults to the global fetch function.

Example Usage

import { oauth2 } from "@glenstack/cf-workers-fetch-helpers";

const gitHubFetch = oauth2(fetch, {
  tokenRefreshed: async ({ accessToken, refreshToken }) => {
    console.log("Tokens have been refreshed!", { accessToken, refreshToken });
  },
  accessToken: "anAccessToken",
  refreshToken: "aRefreshToken",
  tokenEndpoint: "https://github.com/login/oauth/access_token",
  clientID: "anID",
  clientSecret: "aSecret",
});

(async () => {
  const response = await gitHubFetch("https://api.github.com/meta");
})();