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

es-ajax

v1.1.6

Published

Ajax (fetch or xhr2) with promises - an useful JavaScript library for convenient work with ajax requests in a browser.

Downloads

5

Readme

Ajax requests in JavaScript Build Status

Synopsis

This library is for working with (a)synchonously HTTP-requests (HEAD, OPTIONS, GET, POST, PUT, DELETE) in a browser.

All work is based on promises approach. It allows to avoid callback hell.

The library is affording have full control for each external requests. Through API we can cancel current request, abort all active requests, get meta-information for each request-response (starting and ending time, headers). Also we can have number of (non)success responses by define URL. The library allows to create a "singleton" request, which can be sent only once in one time.

Dependencies

Dependencies: object-hash, qs, es-middleware

Installation

npm i -S es-ajax or git clone https://github.com/Zlobin/es-ajax.git cd es-ajax && npm i && webpack

Examples

var ajax = require('es-ajax');

Or after running npm i && webpack inside library path:

<script src="<PATH/TO/LIBRARY>/dist/bundle.js">

You can test some stuff inside /demo/ path.

// GET
ajax('/some/url')
  .get()
  .then(function(response) {
    // ...
  })
  .catch(function(error) {
    // ...
  });

// GET with parameters
ajax('/some/url')
  // /some/url?foo=bar&bar=baz
  .get({
    foo: 'bar',
    bar: 'baz'
  })
  // ...

// POST with parameters
ajax('/some/url')
  .post({
    // ...
    foo: 'bar',
    bar: 'baz'
  })
  .then(function(response) {
    // response.headers
    // response.response

    // ... some stuff
  })
  .catch(function(err) {
    console.log(err);
  });

You can change content-type of request, available types: 'json', 'text', 'html'

ajax('/some/url', {
    type: 'json'
  })
  .get()
  .then(function() {
    // ...
  })
  .catch(function() {
    // ...
  });

Or you can add type manually, via headers:

ajax('/some/url', {
    headers: {
      'Content-type': 'my-type'
    }
  })
  .get()
  .then(function() {
    // ...
  })
  .catch(function() {
    // ...
  });

Middleware is the programming pattern of providing hooks with a resume callback. It will be calling before a request was sent. It is able to cancel request, change URL and headers before sending. May be used, for instance, when you want to use some cache library, allow only some http-methods, like GET and POST, for instance.

Some examples:

var cache = function(next) {
  var response = null;

  // For instance, we don't do cache for URL what contains "noCache" parameter.
  if (this.request.url.indexOf('noCache') > 0) {
    // Check if we already have cached resulst from some MyCache library.
    response = MyCache.get({
      url: request.url,
      method: request.method
    });

    if (response !== null) {
      console.log('Data from a cache.');
      // Do not send request to the server.
      // Return cached response.
      return Promise.resolse({
        response: response,
        headers: []
      });
    } else {
      console.log('Send request to the server.');
      return next();
    }
  } else {
    return next();
  }
};

ajax()
  .use([cache]);

// First request will be send to the server.
ajax('/foo/bar')
  .get()
  .then(function() {
    // Second one - not. We will get data immediately from a cache.
    ajax('/foo/bar')
      .get()
      .then(function() {
        // ...
      })
      .catch(function() {
        // ...
      });
  })
  .catch(function() {
    // ...
  });

Or if you want to allow to use only GET requests:

var onlyGet = function(next) {
  return this.request.method === 'GET' ?
    next() :
    Promise.reject({
      status: 0,
      response: 'Available only "GET" requests',
      headers: []
    });
};

ajax()
  .use([onlyGet]);

ajax('/foo/bar')
  .get()
  .then(function() {
    // ... succeed
  })
  .catch(function() {
    // ...
  });

  ajax('/foo/bar')
    .post()
    .then(function() {
      // ...
    })
    .catch(function() {
      // ... failed
    });

API

Static, may user without any XHR.
  • abortAll Stop all active requests
  • getXhrId Get uniq id of the current request
  • getXhrMeta Get meta info for the current request
  • getAllRequests Get info about each sent request
  • setTimeout Set timeout when reqeust should be canceled automatically
  • use add middleware functions
Non-static, should be used with a XHR (fetch) instance.
  • setOverride Set override for DELETE, PUT requests
  • options Send HTTP OPTIONS request
  • head Send HTTP HEAD request
  • get Send HTTP GET request
  • post Send HTTP POST request
  • put Send HTTP PUT request
  • del Send HTTP DELETE request
  • file Upload a file
  • cancel Candel current active request
  • onProgress Add callback for progress file uploading - returns percentage

Testing

Tests are performed using "mocha", "sinon", "expect" libraries, PhantomJS as a browser and "karma" as a server. Run npm test.

Minifying

You can grab minified versions of es-ajax from /dist path after running webpack.

TODO

  1. Send more than one file
  2. Add more tests
  3. Singleton request
  4. Add custom parameters to the demo
  5. Add polyfill for IE(10, 11) for Promises.