项目作者: surovv

项目描述 :
Light and flexible promise-based http client for browser and node.js
高级语言: JavaScript
项目地址: git://github.com/surovv/luch.git
创建时间: 2017-04-01T13:12:37Z
项目社区:https://github.com/surovv/luch

开源协议:MIT License

下载


Light and flexible promise-based http client built on top of isomorphic-fetch with usefull extra functionality

luch

Code Climate bitHound Overall Score

The luch is light and flexible modular http client built on top of isomorphic-fetch, which build on GitHub’s WHATWG Fetch polyfill.

The luch could be used for both environments as for browser and for node.js, it provides possibility to make requests in easy laconic way with flexible configuration. Also luch uses isomorphic and standardized base under the hood because it built on top of isomorphic-fetch.

Warnings

According to origin isomorphic-fetch docs

  • You must bring your own ES6 Promise compatible polyfill, I suggest es6-promise.

For ease-of-maintenance and backward-compatibility reasons, this library will always be a polyfill. As a “safe” alternative, which does not modify the global, consider fetch-ponyfill.

Installation

NPM

  1. npm install --save luch es6-promise

luch API

luch(url [, options])
  1. require('es6-promise').polyfill();
  2. const {luch} = require('luch');
  3. // or es6
  4. import {luch} from 'luch';
  5. const someHeaders = new Headers();
  6. const someOptions = {
  7. method: 'GET',
  8. headers: someHeaders,
  9. mode: 'cors',
  10. cache: 'default',
  11. };
  12. luch('api.web.com', someOptions)
  13. .then(response => response.json())
  14. .then(data => succFn(data))
  15. .catch(err => errFn(err))

Request method aliases

For convenience aliases have been provided for all popular request methods.

luch.get(url [, params, config])
luch.head(url [, params, config])
luch.options(url [, params, config])
luch.delete(url [, params, config])
luch.post(url [, data, config]])
luch.put(url [, data, config]])
luch.patch(url [, data, config]])
NOTE

By default get head options delete methods stringify params to query-string and post put patch pack data argument to body as json.

  1. luch.get('http://cool.api.com/resource', {limit: 5, offset: 0})
  2. .then(response => handleResponse(response))
  3. .catch(err => handleErr(err));
  4. luch.post('http://cool.api.com/things', {name: 'luch', howCoolItIs: 'very cool'});
  5. const optns = {
  6. headers: new Headers(),
  7. cache: 'default',
  8. };
  9. const vals = {
  10. name: 'dog',
  11. howCoolItIs: 'WUF WUF',
  12. };
  13. luch.put('http://cool.api.com/things', vals, optns);

luchFor

luchFor is method for defining customized luch-like clients with common configuration for multi requests.

luchFor(baseUrl [, baseOptions])
  1. // base.js
  2. import {luchFor} from 'luch';
  3. const localhostUrl = 'http://localhost:3000';
  4. const localhostOptions = {
  5. headers: new Headers({
  6. "Content-Type": "application/json",
  7. }),
  8. };
  9. export const localhostLuch = luchFor(localhostUrl, localhostOptions);
  10. // Voila! Now you can use it like original luch, but with predefined configuration
  11. localhostLuch('/');
  12. // => same as luch(`${localhostUrl}/`, localhostOptions);
  13. const coolArticle = {
  14. title: 'LUCH FOR?? FOR WHAT??!!?',
  15. desc: 'WUF WUF',
  16. };
  17. localhostLuch.post('/articles', coolArticle);
  18. // same as luch.post(`${localhostUrl}/articles`, coolArticle, localhostOptions);
Thats not all!

You can call addToBaseConfig method on luchFor objects, it especially usefull with modules using.

addToBaseConfig(path [, options])
  1. // users.js
  2. import {localhostLuch} from './base';
  3. const usersPath = '/users';
  4. const usersConfig = {
  5. cache: 'default',
  6. };
  7. const usersLuch = localhostLuch.addToBaseConfig(usersPath, usersConfig);
  8. usersLuch.post('/', {name: 'Dude'});
  9. export const updateUser = (id, data) => userLuch.put(`/${id}`, data);
Note

You can pass options argument like in regular luch request, but it will be united with baseOptions by flat merging, so some baseOptions attributes values could be overriden by values from options.

You can read baseUrl and baseOptions values from luchFor object

  1. console.log(localhostLuch.baseUrl, localhostLuch.baseOptions);

Utils

The luch lib provides some extra methods

getAbsoluteUrl(baseUrl)(path)
  1. import {luch, getAbsoluteUrl} from 'luch';
  2. const apiUrl = 'http://localhost:3000';
  3. const withApiUrl = getAbsoluteUrl(apiUrl);
  4. const user = {...};
  5. luch.post(withApiUrl('/users'), user);
  6. // => same as luch.post('http://localhost:3000/users', user)
  7. luch.get(withApiUrl('/resource'));
  8. // => same as luch.get('http://localhost:3000/resource')
  9. luch.get(withApiUrl('/resource2'));
  10. luch.get(withApiUrl('/resource3'));
  11. // calling without path argument will return baseUrl
  12. luch.get(withApiUrl());
  13. // => luch.get('http://localhost:3000')
removeUndefinedAttrs(obj)
  1. import {removeUndefinedAttrs} from 'luch';
  2. const obj = {
  3. a: undefined,
  4. b: null,
  5. c: false,
  6. d: 0,
  7. e: '',
  8. f: 42,
  9. };
  10. removeUndefinedAttrs(obj);
  11. /* => {
  12. b: null,
  13. c: false,
  14. d: 0,
  15. e: '',
  16. f: 42,
  17. }; */
  18. console.log(obj);
  19. // => {a: undefined, b: null, ...}
appendToFormData(body [, formData])

Append or transform object to FormData.

  1. import {luch, appendToFormData} from 'luch';
  2. const data = {/* WUF WUF */};
  3. const options = {
  4. method: 'POST',
  5. body: appendToFormData(data),
  6. };
  7. luch('https://wuf.wuf', options);
getJson

Use it when you need call json method on response

  1. import {luch, getJson} from 'luch';
  2. // from
  3. luch(someUrl)
  4. .then(response => response.json())
  5. .then(data => handleData(data);
  6. // to
  7. luch(someUrl).then(getJson).then(handleData);