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

An XHR/Ajax library with sugar for single page applications.

  • 1.0.9
  • Source
  • npm
  • Socket score

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

Portals

Build Status Join the chat at https://gitter.im/HelpfulHuman/Portals

Portals is a library for making XHR/AJAX requests with some syntactic sugar.

Note: This library assumes you are working in an environment that supports Object.keys, Object.assign and Promises. If you are not then you will need to ensure that a polyfill is in place before using this library.

Getting Started

First things first, you'll need to install the library using 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 Portal instance with some default interceptors that offer baseline functionality for the most common of requests.

import { createPortal } from 'portals';

const http = createPortal({
  globals: {
    hostname: 'https://some-web-service.com',
    headers: {
      Authorization: 'Bearer S#Gwer6in456DFGhje#$5dfgsr5)Lgeryugh'
    }
  }
});

Options

NameTypeDescription
globalsObjectAn object containing a default request template that will be used as the basis to each outgoing request.
jsonBooleanDefaults to true. Enables interceptors for encoding and parsing JSON requests and responses respectively.
queriesBooleanDefaults to true. Enables automatic query string building using a query object for outgoing requests.
paramsBooleanDefaults to true. Enables URL tokens to be replaced with matching values in a params object for outgoing requests.
okStatusesNumber[]An array containing all the "OK" status codes. Any status code not in this list will result an error. You can optionally disable this feature entirely by setting it to false. By default, all 200 and 300 status codes are allowed.
resolveTypesBooleanDefaults to true. Attempts to determine the appropriate Content-Type header for the request based on the body.

Sending Requests

Sending requests isn't all that different from other libraries of this nature. Simply supply a request object with url and method, along with any other request details you may need like a headers object, request body, etc...

The send() method, and the helper methods, will return a standard promise with then() for successful responses and catch() for errors.

http.send({
  method: 'GET',
  url: '/some-endpoint',
  headers: {
    Accept: 'application/json'
  }
}).then(function (res) {
  // do something with response
});

Helpers

Portals offers the typical helper methods for making method specific calls like GET, POST, PUT and DELETE. These return the same result as send().

Note: These examples show possible ways you can use these helpers and assume that the queries and params settings are enabled.

// GET /reports?order=asc
http.get('/reports', { query: { order: 'asc' } })

// POST /articles
http.post('/articles', { subject: 'Hello World' })

// PUT /users/93
http.put('/users/{id}', { name: 'Johnny 5' }, { params: { id: 93 } })

// DELETE /tags/example
http.delete('/tags/example');

Interceptors

Portals is made extensible via "interceptors". These are functions that have the capability to modify request and response data. Portals ships with a few standard interceptors that are added for you based on the configuration that you pass to createPortal().

If you want to cherry pick from the default interceptors, you can find them on the interceptors property and add them with the methods that will be listed below.

import { interceptors } from 'portals';

Adding Interceptors

You can add your own interceptors using either the onRequest() or onResponse() methods. Interceptors are expected to pipe modified input to the next interceptor in the chain, allowing modification in a linear fashion.

Interceptors are added to a Portal instance and are applied to all requests made by that instance. Be sure to take this into account when creating and adding interceptors.

Note: Interceptors will also receive the XHR object for the request as their second argument. However, it is discouraged to modify the XHR object directly unless absolutely necessary!

Request Interceptors

The onRequest() method adds a function that will be run when a request is about to go. It receives the request object (often called req), which contains information like method, url, headers, etc... Interceptors must return an object with strings for method and url.

var http = createPortal();

http.onRequest(function (req) {
  console.log('logging: ', req.url);
  return req;
});

http.get('/my-endpoint'); // "logging: /my-endpoint"

Response Interceptors

The response interceptor is almost identical to the request interceptor, except instead it receives and returns a "response" object (often called req) for the completed request.

var http = createPortal();

http.onResponse(function (res) {
  res.body = 'intercepted!!!';
  return res;
});

http.get('/my-endpoint').then(function (res) {
  console.log(res.body); // "intercepted!!!"
});

Async Interceptors

Interceptors can also be asynchronous if necessary by returning a Promise.

http.onRequest(function (req) {
  return new Promise(function (accept, reject) {
    setTimeout(function () {
      accept(req);
    }, 5000);
  });
});

Error Handlers

Similarly to interceptors, there are error handlers for when things go wrong. Whenever an error occurs during a request, all error handlers will be called with the error before the subscribed .catch() function is invoked.

const http = createPortal();

http.onError(function (err, xhr) {
  // do something due to an error
});

Keywords

FAQs

Package last updated on 08 Sep 2016

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