├── .gitignore ├── .travis.yml ├── LICENSE ├── README.md ├── index.js ├── package.json └── test └── index.js /.gitignore: -------------------------------------------------------------------------------- 1 | # Logs 2 | logs 3 | *.log 4 | 5 | # Runtime data 6 | pids 7 | *.pid 8 | *.seed 9 | 10 | # Directory for instrumented libs generated by jscoverage/JSCover 11 | lib-cov 12 | 13 | # Coverage directory used by tools like istanbul 14 | coverage 15 | 16 | # Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files) 17 | .grunt 18 | 19 | # Compiled binary addons (http://nodejs.org/api/addons.html) 20 | build/Release 21 | 22 | # Dependency directory 23 | # Commenting this out is preferred by some people, see 24 | # https://www.npmjs.org/doc/misc/npm-faq.html#should-i-check-my-node_modules-folder-into-git- 25 | node_modules 26 | 27 | # Users Environment Variables 28 | .lock-wscript 29 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: node_js 2 | node_js: 3 | - "0.12" 4 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2015 Zihua Li 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | 23 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | SuperFetch 2 | ========== 3 | SuperFetch is a promise-based HTTP client for Node.js. It's based on the [request](https://github.com/request/request) library and has an elegant interface. 4 | 5 | [![Build Status](https://travis-ci.org/luin/superfetch.png?branch=master)](https://travis-ci.org/luin/superfetch) 6 | 7 | Install 8 | ------ 9 | 10 | ```shell 11 | $ npm install superfetch 12 | ``` 13 | 14 | Super easy to use 15 | ----------------- 16 | 17 | ```javascript 18 | var fetch = require('superfetch'); 19 | fetch.get('http://example.com').then(function (body) { 20 | // when the status code begins with "2", the response body will be returned. 21 | }).catch(function (response) { 22 | // otherwise, the whole response(including headers) is returned. 23 | }); 24 | 25 | // It's easy to pass the option to the request library 26 | fetch.get.option({ encoding: 'utf8' })('http://example.com').then(//... 27 | 28 | // Chain! 29 | var base = fetch.post.option({ baseSetting: 'foo' }).option({ otherSetting: 'bar' }); 30 | base('http://example1.com', { postbody: {} }).then(//... 31 | base.option({ thirdSetting: 'zoo' })('http://example2.com'); 32 | ``` 33 | 34 | API 35 | ---- 36 | 37 | 1. `fetch[http verb]` will return a VerbInstance. 38 | 2. `VerbInstance.option(settingObj)` or `VerbInstance.option(key, value)` will return a new VerbInstance with the specified settings setted. All options will be passed to the request library except the `transform` which will be introduced later. 39 | 3. `VerbInstance.header(headerObj)` or `VerbInstance.header(key, value)` is an alias for `VerbInstance.option('headers', headerObj)`. 40 | 4. `VerbInstance.auth(user, pass)` is an alias for `VerbInstance.option('auth', { user: user, pass: pass })`. 41 | 5. `VerbInstance(url[, body])` will send a request, and the optionally `body` sets the `json` property of the request library. 42 | 6. `fetch.defaults(defaultOptions)` will create a new fetch instance with a different default options: 43 | ```javascript 44 | var d = fetch.defaults({ encoding: 'utf8' }); 45 | d.post('http://example.com').then(// 46 | ``` 47 | 48 | Transform 49 | --------- 50 | 51 | Both request and response can be transformed. 52 | 53 | ```javascript 54 | fetch.option('transform', { 55 | request: function (options) { 56 | options.method = 'post'; 57 | return options; 58 | }, 59 | response: function (err, resp, body) { 60 | if (err) { 61 | throw err; 62 | } 63 | return resp; 64 | } 65 | }).then(function (resp) { 66 | }); 67 | ``` 68 | 69 | Run tests 70 | --------- 71 | 72 | ```shell 73 | $ npm test 74 | ``` 75 | 76 | More examples can refer to the `test` directory. 77 | 78 | Why build another HTTP client? 79 | ------------- 80 | I'm aware that there are many Node.js HTTP client libraries such as [request](https://github.com/request/request), [superagent](https://github.com/visionmedia/superagent) and [axios](https://github.com/mzabriskie/axios). However, I find out none of these libraries exactly suit my needs. What I want is a library that is powerful, supports promise and has an elegant API, while the fact is request lib is powerful but doesn't support promise, superagent has an elegant API but doesn't as powerful as request lib, and axios lib supports promise but lacks many features I want. So here is SuperFetch. 81 | 82 | Articles 83 | ------- 84 | [DailyJs: AniCollection, SuperFetch](http://dailyjs.com/2015/03/19/anicollection-superfetch/) 85 | -------------------------------------------------------------------------------- /index.js: -------------------------------------------------------------------------------- 1 | var _ = require('lodash'); 2 | var methods = require('methods'); 3 | var request = require('request'); 4 | var Promise = require('bluebird'); 5 | 6 | var superfetch = module.exports = {}; 7 | 8 | var defaultsOptions = { 9 | options: { headers: {} }, 10 | }; 11 | 12 | var proto = { 13 | option: function (key, value) { 14 | var clonedData = _.cloneDeep(this.__data); 15 | if (typeof key === 'object') { 16 | for (var k in key) { 17 | clonedData.options[k] = key[k]; 18 | } 19 | } else { 20 | clonedData.options[key] = value; 21 | } 22 | return wrap(clonedData); 23 | }, 24 | header: function (key, value) { 25 | var clonedData = _.cloneDeep(this.__data); 26 | if (!clonedData.options.headers || typeof clonedData.options.headers !== 'object') { 27 | clonedData.options.headers = {}; 28 | } 29 | if (typeof key === 'object') { 30 | for (var k in key) { 31 | clonedData.options.headers[k] = key[k]; 32 | } 33 | } else { 34 | clonedData.options.headers[key] = value; 35 | } 36 | return wrap(clonedData); 37 | }, 38 | auth: function (user, pass) { 39 | return this.option('auth', { user: user, pass: pass }); 40 | } 41 | }; 42 | 43 | function defaults(obj, options) { 44 | methods.forEach(function (method) { 45 | var data = _.cloneDeep(options); 46 | data.options.method = method; 47 | obj[method] = wrap(data); 48 | }); 49 | } 50 | 51 | defaults(superfetch, defaultsOptions); 52 | 53 | superfetch.defaults = function (options) { 54 | var instance = {}; 55 | defaults(instance, { options: options }); 56 | return instance; 57 | }; 58 | 59 | function wrap (data) { 60 | var newF = fetch.bind(data); 61 | newF.__data = data; 62 | for (var key in proto) { 63 | if (proto.hasOwnProperty(key)) { 64 | newF[key] = proto[key]; 65 | } 66 | } 67 | return newF; 68 | } 69 | 70 | function fetch (url, body) { 71 | var req = _.cloneDeep(this.options); 72 | req.url = url; 73 | if (body) { 74 | req.json = body; 75 | } 76 | 77 | var promise; 78 | if (req.transform && req.transform.request) { 79 | req = req.transform.request(req); 80 | if (typeof req !== 'object' || req === null) { 81 | throw new Error('`transform` should return an object'); 82 | } 83 | if (typeof req.then === 'function') { 84 | promise = req; 85 | } 86 | } 87 | if (!promise) { 88 | promise = Promise.resolve(req); 89 | } 90 | return promise.then(function(req) { 91 | return new Promise(function(resolve, reject) { 92 | request(req, function(err, res, body) { 93 | if (req.transform && req.transform.response) { 94 | try { 95 | resolve(req.transform.response(err, res, body)); 96 | } catch (e) { 97 | throw e; 98 | } 99 | return; 100 | } 101 | if (err) { 102 | reject(err); 103 | } else { 104 | var code = res.statusCode.toString(); 105 | if (code && code[0] === '2') { 106 | resolve(body); 107 | } else { 108 | reject(res); 109 | } 110 | } 111 | }); 112 | }); 113 | }); 114 | } 115 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "superfetch", 3 | "version": "1.1.1", 4 | "description": "A super powerful node.js HTTP client with the support of promise.", 5 | "main": "index.js", 6 | "scripts": { 7 | "test": "mocha" 8 | }, 9 | "keywords": [ 10 | "project", 11 | "http", 12 | "client" 13 | ], 14 | "author": "luin ", 15 | "license": "MIT", 16 | "dependencies": { 17 | "bluebird": "^2.9.14", 18 | "lodash": "^3.5.0", 19 | "methods": "^1.1.1", 20 | "request": "^2.53.0" 21 | }, 22 | "devDependencies": { 23 | "chai": "^2.1.2", 24 | "mocha": "^2.2.1", 25 | "proxyquire": "^1.4.0" 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /test/index.js: -------------------------------------------------------------------------------- 1 | var expect = require('chai').expect; 2 | var proxyquire = require('proxyquire'); 3 | 4 | function defaultHandler (options, callback) { 5 | callback(null, { statusCode: 200 }, options); 6 | } 7 | 8 | var handler = defaultHandler; 9 | var request = function (options, callback) { 10 | handler(options, callback); 11 | }; 12 | 13 | var superfetch = proxyquire('..', { 'request': request }); 14 | 15 | describe('superfetch', function () { 16 | describe('.option', function () { 17 | it('should change the options', function (done) { 18 | superfetch.get.option({ a: 1 }).option('b', 2)('http://a.com').then(function (res) { 19 | expect(res).to.eql({ 20 | method: 'get', 21 | url: 'http://a.com', 22 | headers: {}, 23 | a: 1, 24 | b: 2 25 | }); 26 | done(); 27 | }); 28 | }); 29 | 30 | it('should generate a new instance', function (done) { 31 | var parent = superfetch.get.option({ a: 1 }); 32 | var child1 = parent.option('b', 2); 33 | parent.option('c', 3)('http://a.com').then(function (res) { 34 | expect(res).to.eql({ 35 | method: 'get', 36 | url: 'http://a.com', 37 | headers: {}, 38 | a: 1, 39 | c: 3 40 | }); 41 | done(); 42 | }); 43 | }); 44 | }); 45 | 46 | describe('.header', function () { 47 | it('should change the header', function (done) { 48 | superfetch.get.header({ a: 1 }).header('b', 2)('http://a.com').then(function (res) { 49 | expect(res).to.eql({ 50 | method: 'get', 51 | url: 'http://a.com', 52 | headers: { a: 1, b: 2 }, 53 | }); 54 | done(); 55 | }); 56 | }); 57 | }); 58 | 59 | describe('transform', function () { 60 | it('should reject when status code isnt begin with "2"', function (done) { 61 | handler = function (_, callback) { 62 | callback(null, { statusCode: 400 }); 63 | }; 64 | superfetch.get('http://a.com').catch(function (err) { 65 | handler = defaultHandler; 66 | done(); 67 | }); 68 | }); 69 | 70 | describe('request', function () { 71 | it('should transform request', function (done) { 72 | superfetch.get.option('transform', { 73 | request: function (options) { 74 | options.url = 'http://b.com'; 75 | return options; 76 | } 77 | })('http://a.com').then(function (res) { 78 | expect(res.url).to.eql('http://b.com'); 79 | done(); 80 | }); 81 | }); 82 | }); 83 | 84 | describe('response', function () { 85 | it('should transform request', function (done) { 86 | superfetch.get.option('transform', { 87 | response: function (err, resp, body) { 88 | throw body; 89 | } 90 | })('http://a.com').catch(function (res) { 91 | expect(res.url).to.eql('http://a.com'); 92 | done(); 93 | }); 94 | }); 95 | }); 96 | }); 97 | 98 | describe('request', function () { 99 | it('should use the second param as the body', function (done) { 100 | superfetch.post('http://a.com', { a: 1 }).then(function (res) { 101 | expect(res).to.eql({ 102 | method: 'post', 103 | url: 'http://a.com', 104 | json: { a: 1 }, 105 | headers: {} 106 | }); 107 | done(); 108 | }); 109 | }); 110 | }); 111 | 112 | describe('.defaults', function () { 113 | it('should set the default options', function (done) { 114 | var d = superfetch.defaults({ name: 'bob' }); 115 | d.post('http://a.com').then(function (res) { 116 | expect(res).to.eql({ 117 | method: 'post', 118 | url: 'http://a.com', 119 | name: 'bob' 120 | }); 121 | done(); 122 | }); 123 | }); 124 | }); 125 | }); 126 | --------------------------------------------------------------------------------