├── .gitignore ├── .travis.yml ├── test ├── test-errors.js ├── test-responses.js └── test-basics.js ├── package.json ├── README.md ├── index.js └── LICENSE /.gitignore: -------------------------------------------------------------------------------- 1 | .DS_Store 2 | .nyc_output 3 | coverage 4 | package-lock.json 5 | node_modules 6 | yarn.lock 7 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: node_js 2 | cache: 3 | directories: 4 | # https://twitter.com/maybekatz/status/905213355748720640 5 | - ~/.npm 6 | node_js: 7 | # https://medium.com/@mikeal/stop-supporting-old-releases-70cfa0e04b0c 8 | - 'lts/*' 9 | 10 | # Trigger a push build on master and greenkeeper branches + PRs build on every branches 11 | # Avoid double build on PRs (See https://github.com/travis-ci/travis-ci/issues/1147) 12 | branches: 13 | only: 14 | - master 15 | - /^greenkeeper.*$/ 16 | 17 | stages: 18 | - test 19 | - name: release 20 | if: branch = master AND type IN (push) 21 | 22 | jobs: 23 | include: 24 | - stage: test 25 | script: npm test 26 | after_success: npm run coverage:upload 27 | - stage: release 28 | script: semantic-release 29 | -------------------------------------------------------------------------------- /test/test-errors.js: -------------------------------------------------------------------------------- 1 | const r2 = require('../') 2 | const http = require('http') 3 | const test = require('tap').test 4 | const promisify = require('util').promisify 5 | 6 | let createServer = handler => { 7 | let server = http.createServer(handler) 8 | server._close = server.close 9 | server.close = promisify(cb => server._close(cb)) 10 | server._listen = server.listen 11 | server.listen = promisify((port, cb) => server._listen(port, cb)) 12 | return server 13 | } 14 | 15 | test('cannot connect', async t => { 16 | t.plan(2) 17 | let msg = 'request to http://localhost:1234/ failed, reason: connect ECONNREFUSED 127.0.0.1:1234' 18 | try { 19 | await r2('http://localhost:1234').response 20 | } catch (e) { 21 | t.type(e, 'Error') 22 | t.same(e.message, msg) 23 | } 24 | }) 25 | 26 | test('set read-only property', async t => { 27 | t.plan(2) 28 | let msg = 'Cannot set read-only property.' 29 | let server = createServer((req, res) => { 30 | res.end() 31 | }) 32 | await server.listen(1123) 33 | let r 34 | try { 35 | r = r2('http://localhost:1123/test') 36 | r.json = 'asdf' 37 | } catch (e) { 38 | t.type(e, 'Error') 39 | t.same(e.message, msg) 40 | } 41 | await r.text 42 | await server.close() 43 | }) 44 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "r2", 3 | "version": "0.0.0-development", 4 | "description": "HTTP client. Spiritual successor to request.", 5 | "main": "index.js", 6 | "scripts": { 7 | "commit": "git-cz", 8 | "test": "tap test/test-*.js --100", 9 | "posttest": "standard", 10 | "coverage": "tap test/test-*.js --coverage-report=lcov", 11 | "coverage:upload": "nyc report --reporter=text-lcov | coveralls", 12 | "precommit": "npm test", 13 | "prepush": "npm test", 14 | "commitmsg": "validate-commit-msg", 15 | "semantic-release": "semantic-release" 16 | }, 17 | "keywords": [], 18 | "author": "Mikeal Rogers (http://www.mikealrogers.com)", 19 | "license": "Apache-2.0", 20 | "dependencies": { 21 | "caseless": "^0.12.0", 22 | "node-fetch": "^2.1.2", 23 | "typedarray-to-buffer": "^3.1.2" 24 | }, 25 | "devDependencies": { 26 | "blob-to-buffer": "^1.2.6", 27 | "body": "^5.1.0", 28 | "browserify": "^16.1.0", 29 | "commitizen": "^2.9.6", 30 | "coveralls": "^3.0.0", 31 | "cz-conventional-changelog": "^2.0.0", 32 | "fake-indexeddb": "^2.0.3", 33 | "husky": "^0.14.3", 34 | "lucass": "^4.1.0", 35 | "semantic-release": "^15.0.0", 36 | "standard": "^11.0.0", 37 | "tap": "^12.0.0", 38 | "validate-commit-msg": "^2.14.0" 39 | }, 40 | "browser": { 41 | "node-fetch": false 42 | }, 43 | "repository": { 44 | "type": "git", 45 | "url": "https://github.com/mikeal/r2.git" 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /test/test-responses.js: -------------------------------------------------------------------------------- 1 | const r2 = require('../') 2 | const test = require('tap').test 3 | const http = require('http') 4 | const promisify = require('util').promisify 5 | 6 | let createServer = handler => { 7 | let server = http.createServer(handler) 8 | server._close = server.close 9 | server.close = promisify(cb => server._close(cb)) 10 | server._listen = server.listen 11 | server.listen = promisify((port, cb) => server._listen(port, cb)) 12 | return server 13 | } 14 | 15 | let url = 'http://localhost:1123/test' 16 | 17 | test('arraybuffer', async t => { 18 | t.plan(2) 19 | let server = createServer(async (req, res) => { 20 | t.same(req.url, '/test') 21 | res.end('test') 22 | }) 23 | await server.listen(1123) 24 | t.same(Buffer.from(await r2(url).arrayBuffer), Buffer.from('test')) 25 | await server.close() 26 | }) 27 | 28 | test('blob', async t => { 29 | t.plan(2) 30 | let server = createServer(async (req, res) => { 31 | t.same(req.url, '/test') 32 | res.end('test') 33 | }) 34 | await server.listen(1123) 35 | let blob = await r2(url).blob 36 | t.same(blob.size, 4) 37 | await server.close() 38 | }) 39 | 40 | test('multiple bodies', async t => { 41 | t.plan(3) 42 | let server = createServer(async (req, res) => { 43 | t.same(req.url, '/test') 44 | res.setHeader('content-type', 'application/json') 45 | res.end(JSON.stringify({ok: true})) 46 | }) 47 | await server.listen(1123) 48 | let r = r2.get(url) 49 | t.same(await r.json, {ok: true}) 50 | t.same(await r.text, JSON.stringify({ok: true})) 51 | await server.close() 52 | }) 53 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # r2 2 | 3 | [![Build Status](https://travis-ci.org/mikeal/r2.svg?branch=master)](https://travis-ci.org/mikeal/r2) [![Coverage Status](https://coveralls.io/repos/github/mikeal/r2/badge.svg?branch=master)](https://coveralls.io/github/mikeal/r2?branch=master) [![Greenkeeper badge](https://badges.greenkeeper.io/mikeal/r2.svg)](https://greenkeeper.io/) 4 | 5 | Early in Node.js I wrote an HTTP client library called `request`. It evolved 6 | along with Node.js and eventually became very widely depended upon. 7 | 8 | A lot has changed since 2010 and I've decided to re-think what a simple 9 | HTTP client library should look like. 10 | 11 | This new library, `r2`, is a completely new approach from `request`. 12 | 13 | * Rather than being built on top of the Node.js Core HTTP library and 14 | shimmed for the browser, `r2` is built on top of the browser's 15 | Fetch API and shimmed for Node.js. 16 | * APIs are meant to be used with async/await, which means they are 17 | based on promises. 18 | 19 | ```javascript 20 | const r2 = require('r2') 21 | 22 | let html = await r2('https://www.google.com').text 23 | ``` 24 | 25 | Simple JSON support. 26 | 27 | ```javascript 28 | let obj = {ok: true} 29 | 30 | let resp = await r2.put('http://localhost/test.json', {json: obj}).json 31 | ``` 32 | 33 | Simple headers support. 34 | 35 | ```javascript 36 | let headers = {'x-test': 'ok'} 37 | 38 | let res = await r2('http://localhost/test', {headers}).response 39 | ``` 40 | 41 | Being written to the Fetch API is a huge benefit for browser users. 42 | 43 | When running through browserify `request` is ~2M uncompressed and ~500K compressed. `r2` is only 66K uncompressed and 16K compressed. 44 | -------------------------------------------------------------------------------- /index.js: -------------------------------------------------------------------------------- 1 | /* globals fetch, Headers */ 2 | /* istanbul ignore next */ 3 | if (!process.browser) { 4 | global.fetch = require('node-fetch') 5 | global.Headers = global.fetch.Headers 6 | } 7 | 8 | const caseless = require('caseless') 9 | const toTypedArray = require('typedarray-to-buffer') 10 | 11 | const makeHeaders = obj => new Headers(obj) 12 | 13 | function makeBody (value) { 14 | // TODO: Streams support. 15 | if (typeof value === 'string') { 16 | value = Buffer.from(value) 17 | } 18 | /* Can't test Blob types in Node.js */ 19 | /* istanbul ignore else */ 20 | if (Buffer.isBuffer(value)) { 21 | value = toTypedArray(value) 22 | } 23 | return value 24 | } 25 | 26 | class R2 { 27 | constructor (...args) { 28 | this.opts = { method: 'GET' } 29 | this._headers = {} 30 | this._caseless = caseless(this._headers) 31 | 32 | let failSet = () => { 33 | throw new Error('Cannot set read-only property.') 34 | } 35 | const resolveResWith = way => resp => resp.clone()[way]() 36 | 37 | /* formData isn't implemented in the shim yet */ 38 | const ways = ['json', 'text', 'arrayBuffer', 'blob', 'formData'] 39 | ways.forEach(way => 40 | Object.defineProperty(this, way, { 41 | get: () => this.response.then(resolveResWith(way)), 42 | set: failSet 43 | }) 44 | ) 45 | this._args(...args) 46 | 47 | this.response = Promise.resolve().then(() => this._request()) 48 | } 49 | 50 | _args (...args) { 51 | let opts = this.opts 52 | if (typeof args[0] === 'string') { 53 | opts.url = args.shift() 54 | } 55 | if (typeof args[0] === 'object') { 56 | opts = Object.assign(opts, args.shift()) 57 | } 58 | this.setHeaders(opts.headers) 59 | this.opts = opts 60 | } 61 | 62 | method (verb, ...args) { 63 | this.opts.method = verb.toUpperCase() 64 | this._args(...args) 65 | return this 66 | } 67 | _request () { 68 | let url = this.opts.url 69 | delete this.opts.url 70 | 71 | if (this.opts.json) { 72 | this.opts.body = JSON.stringify(this.opts.json) 73 | this.setHeader('content-type', 'application/json') 74 | delete this.opts.json 75 | } 76 | 77 | if (this.opts.body) { 78 | this.opts.body = makeBody(this.opts.body) 79 | } 80 | 81 | // TODO: formData API. 82 | 83 | this.opts.headers = makeHeaders(this._headers) 84 | 85 | return fetch(url, this.opts) 86 | } 87 | setHeaders (obj = {}) { 88 | for (let key in obj) { 89 | this._caseless.set(key, obj[key]) 90 | } 91 | return this 92 | } 93 | setHeader (key, value) { 94 | this.setHeaders({ [key]: value }) 95 | } 96 | } 97 | 98 | module.exports = (...args) => new R2(...args) 99 | module.exports.put = (...args) => new R2().method('put', ...args) 100 | module.exports.get = (...args) => new R2().method('get', ...args) 101 | module.exports.post = (...args) => new R2().method('post', ...args) 102 | module.exports.head = (...args) => new R2().method('head', ...args) 103 | module.exports.patch = (...args) => new R2().method('patch', ...args) 104 | module.exports.delete = (...args) => new R2().method('delete', ...args) 105 | -------------------------------------------------------------------------------- /test/test-basics.js: -------------------------------------------------------------------------------- 1 | const r2 = require('../') 2 | const test = require('tap').test 3 | const http = require('http') 4 | const promisify = require('util').promisify 5 | const body = promisify(require('body')) 6 | 7 | let createServer = handler => { 8 | let server = http.createServer(handler) 9 | server._close = server.close 10 | server.close = promisify(cb => server._close(cb)) 11 | server._listen = server.listen 12 | server.listen = promisify((port, cb) => server._listen(port, cb)) 13 | return server 14 | } 15 | 16 | let url = 'http://localhost:1123/test' 17 | 18 | test('basic get', async t => { 19 | t.plan(2) 20 | let server = createServer((req, res) => { 21 | t.same(req.url, '/test') 22 | res.end('ok') 23 | }) 24 | await server.listen(1123) 25 | t.same(await r2(url).text, 'ok') 26 | await server.close() 27 | }) 28 | 29 | test('basic put', async t => { 30 | t.plan(3) 31 | let server = createServer(async (req, res) => { 32 | t.same(req.url, '/test') 33 | t.same(await body(req), 'test') 34 | res.end('ok') 35 | }) 36 | await server.listen(1123) 37 | t.same(await r2.put(url, {body: 'test'}).text, 'ok') 38 | await server.close() 39 | }) 40 | 41 | test('json put and get', async t => { 42 | t.plan(4) 43 | let server = createServer(async (req, res) => { 44 | t.same(req.url, '/test') 45 | t.same(req.headers['content-type'], 'application/json') 46 | t.same(await body(req), '{"t":"test"}') 47 | res.setHeader('content-type', 'application/json') 48 | res.end(JSON.stringify({ok: true})) 49 | }) 50 | await server.listen(1123) 51 | t.same(await r2.put(url, {json: {t: 'test'}}).json, {ok: true}) 52 | await server.close() 53 | }) 54 | 55 | test('headers', async t => { 56 | t.plan(3) 57 | let server = createServer(async (req, res) => { 58 | t.same(req.url, '/test') 59 | t.same(req.headers['x-test'], 'blah') 60 | res.end('test') 61 | }) 62 | await server.listen(1123) 63 | t.same(await r2.get(url, {headers: {'x-test': 'blah'}}).text, 'test') 64 | await server.close() 65 | }) 66 | 67 | test('post', async t => { 68 | t.plan(3) 69 | let server = createServer(async (req, res) => { 70 | t.same(req.url, '/test') 71 | t.same(req.method, 'POST') 72 | res.end('test') 73 | }) 74 | await server.listen(1123) 75 | t.same(await r2.post(url).text, 'test') 76 | await server.close() 77 | }) 78 | 79 | test('head', async t => { 80 | t.plan(3) 81 | let server = createServer(async (req, res) => { 82 | t.same(req.url, '/test') 83 | t.same(req.method, 'HEAD') 84 | res.end('test') 85 | }) 86 | await server.listen(1123) 87 | t.same(await r2.head(url).text, '') 88 | await server.close() 89 | }) 90 | 91 | test('delete', async t => { 92 | t.plan(3) 93 | let server = createServer(async (req, res) => { 94 | t.same(req.url, '/test') 95 | t.same(req.method, 'DELETE') 96 | res.end('test') 97 | }) 98 | await server.listen(1123) 99 | t.same(await r2.delete(url).text, 'test') 100 | await server.close() 101 | }) 102 | 103 | test('patch', async t => { 104 | t.plan(3) 105 | let server = createServer(async (req, res) => { 106 | t.same(req.url, '/test') 107 | t.same(req.method, 'PATCH') 108 | res.end('test') 109 | }) 110 | await server.listen(1123) 111 | t.same(await r2.patch(url).text, 'test') 112 | await server.close() 113 | }) 114 | 115 | test('put buffer', async t => { 116 | t.plan(3) 117 | let server = createServer(async (req, res) => { 118 | t.same(req.url, '/test') 119 | t.same(await body(req), 'test') 120 | res.end('ok') 121 | }) 122 | await server.listen(1123) 123 | t.same(await r2.put(url, {body: Buffer.from('test')}).text, 'ok') 124 | await server.close() 125 | }) 126 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | 3 | Version 2.0, January 2004 4 | 5 | http://www.apache.org/licenses/ 6 | 7 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 8 | 9 | 1. Definitions. 10 | 11 | "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. 16 | 17 | "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. 18 | 19 | "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. 20 | 21 | "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. 22 | 23 | "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). 24 | 25 | "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. 26 | 27 | "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." 28 | 29 | "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 30 | 31 | 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 32 | 33 | 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 34 | 35 | 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: 36 | 37 | You must give any other recipients of the Work or Derivative Works a copy of this License; and 38 | 39 | You must cause any modified files to carry prominent notices stating that You changed the files; and 40 | 41 | You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and 42 | 43 | If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 44 | 45 | 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 46 | 47 | 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 48 | 49 | 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 50 | 51 | 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 52 | 53 | 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. 54 | 55 | END OF TERMS AND CONDITIONS --------------------------------------------------------------------------------