Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

portals

Package Overview
Dependencies
Maintainers
2
Versions
29
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

portals

Client-side HTTP requests with middleware support.

  • 2.1.1
  • Source
  • npm
  • Socket score

Version published
Weekly downloads
107
increased by105.77%
Maintainers
2
Weekly downloads
 
Created
Source

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.

FieldTypeDescription
urlstringThe endpoint address that we'll making a request to. This field is required.
methodstringThe HTTP method used for the request. Defaults to "GET".
headersobjectAn object literal containing all of the HTTP headers for the request. Automatically gets mapped to the XHR object for the request.
bodyanyThe 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.
withCredentialsbooleanSets 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.

FieldTypeDescription
xhrXMLHttpRequestThe XHR instance used to perform the request.
statusCodenumberThe HTTP status code returned by the server. Should be within the 200 - 299 for OK or accepted requests.
contentTypestringThe MIME type for the response provided by the Content-Type response header.
headersobjectResponse headers in a simplified object literal.
bodyanyThe 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"))

withBearer(getToken)

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

import {withBearer} from "portals";

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

Keywords

FAQs

Package last updated on 19 Jun 2018

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc