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

universal-rx-request

v1.0.3

Published

Lightweight HTTP requests library based on superagent that returns a RxJS 5 observable. This library works on browser and server side.

Downloads

248

Readme

universal-rx-request

codecov npm npm npm

Lightweight HTTP requests library based on superagent that returns a RxJS 5 observable. This library works on browser and server side.

Install

This library has peer dependencies of rxjs@>=5.0.1 and superagent@>=3.3.0. To install via npm for node environment:

npm install --save superagent rxjs universal-rx-request

To install on the browser:

<script type="text/javascript" src="/lib/index.js"></script>

The library exposed a global variable called rxRequest. It also works with AMD api.

Basic Example

The library exposes a function which makes directly the HTTP request depending of the configuration you give. The request will return an observable.

import rxRequest from 'universal-rx-request';

rxRequest({ method: 'get', url: 'https://api.ipify.org?format=json' })
  .subscribe(result => console.log(result.body.ip), console.error);
// print your current ip

rxRequest({ method: 'get', url: 'https://wrong-api.com/notFound' })
  .subscribe(result => console.log, error => console.error(error.error.errno));
// print ENOTFOUND

Works great with redux and redux-observable

You can import rx extensions which allow you to have more controls on the different steps that the request will going through (fetching => success|error).

import rxRequest from 'universal-rx-request';

rxRequest.importRxExtensions(); // will add operators for the observables. You only have to do once

rxRequest({ method: 'get', url: 'https://api.ipify.org?format=json' })
  .mapToAction({ type: 'get_my_ip' })
  .subscribe(console.log, console.error);
// print the emitted items as a stream
//  |--- { type: 'get_my_ip_fetching', requestStatus: 'fetching' } ------ { type: 'get_my_ip_success', requestStatus: 'success',  data: reponse } ----|

rxRequest({ method: 'get', url: 'https://wrong-api.com/notFound' })
  .mapToAction({ type: 'get_my_ip' })
  .subscribe(console.log, console.error);
// print the emitted items as a stream
//  |--- { type: 'get_my_ip_fetching', requestStatus: 'fetching' } ------ { type: 'get_my_ip_error', requestStatus: 'error',  error: error } ----|

Thanks to this rx extension you will be able to handle your state after each step of the HTTP request.

The rx extensions provide some other useful operators:

import rxRequest from 'universal-rx-request';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/observable/of';

rxRequest.importRxExtensions();

rxRequest({ method: 'get', url: 'https://api.ipify.org?format=json' })
  .mapToAction({ type: 'get_my_ip' })
  .mergeMapOnSucceedRequest(result => Observable.of({ ip: result.data.body.ip }))
  .subscribe(console.log, console.error);
// print the emitted items as a stream
//  |--- { type: 'get_my_ip_fetching', requestStatus: 'fetching' } ------ { ip: 'xxx.xxx.xxx.x' } ----|

Once you map the request to an action with maptoAction, We recommand you to use the extended operators to deal with succeed or failure request. these are the extended operators which may be useful:

  • throwErrorOnFailedRequest(): It will throw an error if the result of the http request is an error. To handle the error, you will have to catch it in the observable flow.
  • mergeMapOnSucceedRequest((result) => {...}): It acts like a classic mergeMap in the Rx world except that it will mergeMap only on succeed request (not fetching or error status). The function given as argument has to return an observable.
  • flatMapOnSucceedRequest((result) => {...}): It's an alias for mergeMapOnSucceedRequest.
  • concatMapOnSucceedRequest((result) => {...}): It's like mergeMapOnSucceedRequest except that it use the concatMap operator.
  • doOnSucceedRequest((result) => {...}): It's like mergeMapOnSucceedRequest except that it use the do operator to do side effects.
  • filterOnSucceedRequest(): It's like mergeMapOnSucceedRequest except that it use the filter operator.

I invite you to check out the test folder which contains great example of how to use these operators correctly.

APIs

rxRequest(settings)

Function that will make the HTTP request and returns an observable. Shape of the settings (only url and method fields are required):

 {
  url: 'https://...',
  method: 'get|post|update|...',
  query: {},
  data: {},
  options: {
    only2xx: true|false,
    agent: superagent.agent(),
    json: true|false,
    headers: {},
    withCredentials: true|false,
    responseType: 'blob|...',
    timeout: {
      response: 5000,
      deadline: 60000,
    },
    auth: ['tobi', 'learnboost'],
    redirects: 2,
    attaches: [ ['file', 'test.png'], ...],
    fields: [ ['user', 'Bob'], ...],
  }
 }

The function will return an observable which will emit an object corresponding to the response of the HTTP request. If an error occurs, the observable will emit an error which can be catch in the observable flow. The error emitted will be an object containing the error and response field. For more details about the shapes of the error and response object, please check the superagent library.

rxRequest.STATUS

It's an object containg all the different possible state of the HTTP request:

{
  FETCHING: 'fetching',
  SUCCESS: 'success',
  ERROR: 'error',
}

rxRequest.getStatus(action, status)

Facility to get the type of the emitted action depending of the action object ({ type: ... }) and the status (rxRequest.STATUS).

rxRequest.importRxExtensions()

Function to extend the observable with new operators described above.