portals
Client-side HTTP requests with middleware support.
Last updated 2 years ago by hello-helpfulhuman .
MIT · Repository · Bugs · Original npm · Tarball · package.json
$ cnpm install portals 
SYNC missed versions from official npm registry.

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: "..." } }

Current Tags

  • 3.1.5                                ...           latest (2 years ago)

29 Versions

  • 3.1.5                                ...           2 years ago
  • 3.1.4                                ...           2 years ago
  • 3.1.3                                ...           2 years ago
  • 3.1.2                                ...           2 years ago
  • 3.1.1                                ...           2 years ago
  • 3.1.0                                ...           2 years ago
  • 3.0.2                                ...           2 years ago
  • 3.0.1                                ...           2 years ago
  • 3.0.0                                ...           2 years ago
  • 2.1.2                                ...           2 years ago
  • 2.1.1                                ...           2 years ago
  • 2.1.0                                ...           3 years ago
  • 2.0.0                                ...           3 years ago
  • 1.0.9                                ...           4 years ago
  • 1.0.8                                ...           4 years ago
  • 1.0.7                                ...           4 years ago
  • 1.0.6                                ...           4 years ago
  • 1.0.5                                ...           4 years ago
  • 1.0.4                                ...           4 years ago
  • 1.0.3                                ...           4 years ago
  • 1.0.2                                ...           4 years ago
  • 1.0.1                                ...           4 years ago
  • 1.0.0                                ...           4 years ago
  • 0.2.2                                ...           4 years ago
  • 0.2.1                                ...           4 years ago
  • 0.2.0                                ...           4 years ago
  • 0.1.3                                ...           5 years ago
  • 0.1.1                                ...           5 years ago
  • 0.1.0                                ...           5 years ago
Downloads
Today 0
This Week 0
This Month 0
Last Day 0
Last Week 0
Last Month 0
Dependencies (0)
None
Dev Dependencies (7)
Dependents (0)
None

Copyright 2014 - 2016 © taobao.org |