1.0.0-alpha.1 • Published 7 years ago

rxhr v1.0.0-alpha.1

Weekly downloads
5
License
MIT
Repository
github
Last release
7 years ago

rxhr

A tiny Observable based HTTP client

Travis Code Coverage David npm npm JavaScript Style Guide MIT License

The current size of rxhr/dist/rxhr.umd.min.js is:

gzip size

Install

This project uses node and npm. Go check them out if you don't have them locally installed.

$ npm i rxhr

Then with a module bundler like rollup or webpack, use as you would anything else:

// using ES6 modules
import rxhr from 'rxhr'

// using CommonJS modules
var rxhr = require('rxhr')

The UMD build is also available on unpkg:

<script src="https://unpkg.com/rxhr/dist/rxhr.umd.js"></script>

You can find the library on window.rhxr.

Usage

import rxhr from 'rxhr'

const req$ = rxhr({
  method: 'get',
  responseType: 'json',
  url: 'https://jsonplaceholder.typicode.com/posts'
})
.subscribe(
  res => res.json().forEach(e => console.log(e.title)),
  err => console.log(err),
  () => console.log('completed')
)

// abort request
req$.unsubscribe()

It's easy to combine with rxjs

const req$ = rxhr({
  method: 'get',
  responseType: 'json',
  url: 'https://jsonplaceholder.typicode.com/posts'
})

const sub$ = Rx.Observable
.timer(0, 1000)
.switchMap(() => Rx.Observable.from(req$))
.map(res => res.json())
.subscribe(
  res => console.log(res.length),
  err => console.log('err', err),
  () => console.log('completed')
)

It supports blob request type

const req$ = rxhr({
  method: 'get',
  responseType: 'blob',
  url: 'https://avatars2.githubusercontent.com/u/82070?v=3&s=460'
})

const sub$ = Rx.Observable
.timer(0, 1000)
.take(3)
.switchMap(() => Rx.Observable.from(req$))
.map(res => res.blob())
.subscribe(
  blob => {
    const fr = new FileReader();
    fr.onload = function(e) {
      const img = new Image(); // width, height values are optional params
      img.src = e.target.result
      document.body.appendChild(img)
    }
    fr.readAsDataURL(blob);
  },
  err => console.log('err', err),
  () => console.log('completed')
)

Tests

$ npm run test

MIT License © Alessandro Arnodo