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

portals

v3.1.5

Published

Client-side HTTP requests with middleware support.

Downloads

106

Readme

Portals

Portals is a library for making XHR requests with middleware support.

Getting Started

Install the library with npm:

npm install --save portals

Once installed, you can import the createPortal() function to get up and running immediately. This function is a factory that will set up a new "portal" for creating HTTP requests.

import {createPortal} from "portals";

const http = createPortal();

http({ url: "http://example.com/some/endpoint" }).then(res => ...)

The example above doesn't do much outside of creating an XHR request for you. However, the usefulness of this library lies in its use of middleware. The example below will stringify and parse JSON for the request and response data, prefix given URLs with the desired hostname and add the Authorization header with a Bearer token.

Note: Don't be afraid to have multiple portal functions for different use cases. The returned function is incredibly simple and contains little overhead.

import {createPortal, supportsJson, withPrefix, withBearer} from "portals";

const exampleApi = createPortal(
  supportsJson(),
  withPrefix("https://api.example.com")
  withBearer(req => localStorage.getItem("apiToken"))
);

The Request Object

The table below outlines the fields supported by all requests, regardless of middleware.

| Field | Type | Description | | ------------------- | --------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | url | string | The endpoint address that we'll making a request to. This field is required. | | method | string | The HTTP method used for the request. Defaults to "GET". | | headers | object | An object literal containing all of the HTTP headers for the request. Automatically gets mapped to the XHR object for the request. | | body | any | The request body used by POST, PUT and PATCH requests. By default, you should use string or FormData formats unless you have middleware in place to handle type conversions. | | withCredentials | boolean | Sets the value of the .withCredentials property of the XHR instance for the request in order to allow secured cross-domain calls. Defaults to true. |

The Response Object

The table below represents the object generated for a response before middleware is applied.

| Field | Type | Description | | --------------- | ---------------- | --------------------------------------------------------------------------------------------------------- | | xhr | XMLHttpRequest | The XHR instance used to perform the request. | | statusCode | number | The HTTP status code returned by the server. Should be within the 200 - 299 for OK or accepted requests. | | contentType | string | The MIME type for the response provided by the Content-Type response header. | | headers | object | Response headers in a simplified object literal. | | body | any | The body of the response. |

Error Handling

Because every endpoint handles errors differently, the errors that are reported to your Promise's .catch() handler are only for fatal errors related to problems within your middleware or the XHR call itself. Instead, you can check the status code on the response object that is returned.

Middleware

The middleware system employed by this library is based on Promises and should feel familiar to people who have used libraries with similar patterns (like Koa). Middleware in Portals is a function that accepts a Request object and a next() function that will invoke and return the result of the next middleware in the stack. The result of next() will always be a Promise.

Note: Portals supports native promises and can safely be used with the async/await keywords.

function myMiddleware(request, next) {
  // do something with the request
  return next().then(function(response) {
    // do something with the response
  });
}

Included Middleware

supportsJson()

Encodes object literal body values into JSON requests and automatically parses JSON response bodies.

withPrefix(prefix)

Prefix the request URL with either a full hostname or partial URI.

import {withPrefix} from "portals";

// converts `/foo` to `/api/foo` and...
// converts `http://example.com` to `http://example.com/api`
withPrefix("/api")

// converts `/foo` to `http://example.com/foo` but
// leaves `http://somewhere.else.com/foo` alone
withPrefix("http://example.com")

withHeader(name, value, override = false)

Add a header to your request, either as a default if none is provided or as a constant override. The second argument, value, can also be a function that receives the request object.

import {withHeader} from "portals";

// Default header
withHeader("Content-Type", "application/json")

// Constant override header
withHeader("Content-Type", "application/json", true)

// Dynamic header value
withHeader("Content-Type", (req) => (req.body instanceof FormData ? "multipart/form-data" : "application/json"))

withAuthorization(getToken)

Passes the request object to the given getToken method to generate a value for the Authorization header. Optionally supports a custom string prefix as the second value that is only applied when a string value is successfully returned from the getToken function call.

import {withAuthorization} from "portals";

withAuthorization(req => localStorage.getItem("apiToken"))
// { headers: { Authorization: "${apiToken}" } }

withAuthorization(req => localStorage.getItem("apiToken"), "Token ")
// { headers: { Authorization: "Token ${apiToken}" } }

withBearer(getToken)

Passes the request object to the given getToken method to generate a Bearer token for the Authorization header.

import {withBearer} from "portals";

withBearer(req => localStorage.getItem("apiToken"))
// { headers: { Authorization: "Bearer ${apiToken}" } }

withXSRFToken(cookieName = "XSRF-TOKEN", headerName = "X-XSRF-TOKEN")

Passes along the value for the specified cookieName to the server via the header specified by headerName.

import {withXSRFToken} from "portals";

withXSRFToken()
// { headers: { X-XSRF-TOKEN: "..." } }