├── .babelrc ├── test ├── .eslintrc └── test.js ├── .gitignore ├── webpack.config.js ├── .eslintrc ├── .editorconfig ├── .travis.yml ├── LICENSE ├── package.json ├── modules └── index.js └── README.md /.babelrc: -------------------------------------------------------------------------------- 1 | { 2 | "presets": [ 3 | "stage-0", 4 | "es2015" 5 | ] 6 | } 7 | -------------------------------------------------------------------------------- /test/.eslintrc: -------------------------------------------------------------------------------- 1 | { 2 | "env": { 3 | "mocha": true 4 | }, 5 | "rules": { 6 | "global-require": 0 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .idea/ 2 | .npm/ 3 | coverage/ 4 | node_modules/ 5 | lib/ 6 | umd/ 7 | logs 8 | *.log 9 | npm-debug.log* 10 | -------------------------------------------------------------------------------- /webpack.config.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | 3 | output: { 4 | library: 'FetchHttpClient', 5 | libraryTarget: 'umd', 6 | }, 7 | 8 | module: { 9 | loaders: [ 10 | { test: /\.js$/, exclude: /node_modules/, loader: 'babel' }, 11 | ], 12 | }, 13 | 14 | }; 15 | -------------------------------------------------------------------------------- /.eslintrc: -------------------------------------------------------------------------------- 1 | { 2 | "parser": "babel-eslint", 3 | "extends": "airbnb", 4 | "ecmaFeatures": { 5 | "experimentalObjectRestSpread": true 6 | }, 7 | "rules": { 8 | "no-shadow": 0, 9 | "no-param-reassign": 0 10 | }, 11 | "globals": { 12 | "define": true, 13 | "require": true, 14 | "fetch": true 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /.editorconfig: -------------------------------------------------------------------------------- 1 | # EditorConfig is awesome: http://EditorConfig.org 2 | 3 | # top-most EditorConfig file 4 | root = true 5 | 6 | # Unix-style newlines with a newline ending every file 7 | [*] 8 | end_of_line = lf 9 | insert_final_newline = true 10 | charset = utf-8 11 | indent_style = space 12 | 13 | # JS indent size is 2 14 | [**.{js,jsx,json,yml,html,less}] 15 | indent_size = 2 16 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: node_js 2 | node_js: 3 | - "0.10" 4 | - "0.12" 5 | - "4.4" 6 | - "5.11" 7 | - "6.3" 8 | - "8.9" 9 | sudo: false 10 | cache: 11 | bundler: true 12 | directories: 13 | - node_modules 14 | before_install: 15 | - "npm install" 16 | script: 17 | - "npm run clean" 18 | - "npm run lint" 19 | - "npm run test-travis" 20 | - "npm run build" 21 | after_script: 22 | - "test -e ./coverage/lcov.info && npm install coveralls@2 && cat ./coverage/lcov.info | coveralls" 23 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2016 Max Liu 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 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "fetch-http-client", 3 | "version": "1.1.0", 4 | "description": "A http client wrapper for fetch api with middleware support.", 5 | "main": "lib", 6 | "files": [ 7 | "lib", 8 | "umd" 9 | ], 10 | "scripts": { 11 | "lint": "eslint modules test", 12 | "test": "mocha --compilers js:babel-core/register --reporter spec --bail test/", 13 | "test-cov": "babel-node ./node_modules/.bin/babel-istanbul cover _mocha -- --reporter dot test/", 14 | "test-travis": "babel-node ./node_modules/.bin/babel-istanbul cover _mocha --report lcovonly -- --reporter dot test/", 15 | "build": "babel ./modules -d lib && webpack modules/index.js umd/fetch-http-client.js && webpack -p modules/index.js umd/fetch-http-client.min.js", 16 | "clean": "rm -rf lib umd" 17 | }, 18 | "pre-commit": [ 19 | "lint" 20 | ], 21 | "repository": { 22 | "type": "git", 23 | "url": "git+https://github.com/starlight36/fetch-http-client.git" 24 | }, 25 | "keywords": [ 26 | "fetch", 27 | "http", 28 | "request" 29 | ], 30 | "bugs": { 31 | "url": "https://github.com/starlight36/fetch-http-client/issues" 32 | }, 33 | "homepage": "https://github.com/starlight36/fetch-http-client#readme", 34 | "license": "MIT", 35 | "dependencies": { 36 | "query-string": "^4.1.0" 37 | }, 38 | "devDependencies": { 39 | "babel-cli": "~6.8.0", 40 | "babel-core": "^6.8.0", 41 | "babel-eslint": "~6.0.4", 42 | "babel-istanbul": "^0.11.0", 43 | "babel-loader": "^6.2.4", 44 | "babel-preset-es2015": "~6.6.0", 45 | "babel-preset-stage-0": "^6.5.0", 46 | "eslint": "~2.9.0", 47 | "eslint-config-airbnb": "~8.0.0", 48 | "eslint-plugin-import": "~1.7.0", 49 | "eslint-plugin-jsx-a11y": "~1.0.4", 50 | "eslint-plugin-react": "~5.0.1", 51 | "flow-bin": "^0.24.2", 52 | "istanbul": "^0.4.4", 53 | "mocha": "^3.0.2", 54 | "pre-commit": "1.x", 55 | "webpack": "~1.13.0" 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /modules/index.js: -------------------------------------------------------------------------------- 1 | import { stringify } from 'query-string'; 2 | 3 | export default class FetchHttpClient { 4 | 5 | constructor(baseUrl) { 6 | this.baseUrl = baseUrl || ''; 7 | this.middlewareId = 1; 8 | this.middlewares = []; 9 | } 10 | 11 | addMiddleware(middleware) { 12 | if (!middleware.middlewareId) { 13 | middleware.middlewareId = this.middlewareId++; 14 | } 15 | this.middlewares.push(middleware); 16 | 17 | return this; 18 | } 19 | 20 | removeMiddleware(middleware) { 21 | if (!middleware.middlewareId) { 22 | return this; 23 | } 24 | 25 | if (this.middlewares[middleware.middlewareId]) { 26 | delete this.middlewares[middleware.middlewareId]; 27 | } 28 | 29 | return this; 30 | } 31 | 32 | fetch(path, options = {}) { 33 | if (typeof fetch !== 'function') { 34 | throw new TypeError('fetch() function not available'); 35 | } 36 | 37 | options = { headers: {}, ...options }; 38 | 39 | const url = this.resolveUrl(path, options.uriParams || {}); 40 | const responseMiddlewares = []; 41 | const requestPromise = this.middlewares.reduce( 42 | (promise, middleware) => promise.then(request => { 43 | const result = middleware(request); 44 | if (typeof result === 'function') { 45 | responseMiddlewares.push(result); 46 | } 47 | return (result && typeof result !== 'function') ? result : request; 48 | }), 49 | Promise.resolve({ url, path, options, fetch }) 50 | ).then(request => request.fetch(request.url, request.options)); 51 | 52 | return requestPromise.then(response => responseMiddlewares.reduce( 53 | (promise, middleware) => promise.then(response => middleware(response) || response), 54 | Promise.resolve(response) 55 | )); 56 | } 57 | 58 | request(path, method, options = {}) { 59 | return this.fetch(path, { ...options, method }); 60 | } 61 | 62 | get(path, options = {}) { 63 | return this.request(path, 'GET', options); 64 | } 65 | 66 | post(path, options = {}) { 67 | return this.request(path, 'POST', options); 68 | } 69 | 70 | put(path, options = {}) { 71 | return this.request(path, 'PUT', options); 72 | } 73 | 74 | delete(path, options = {}) { 75 | return this.request(path, 'DELETE', options); 76 | } 77 | 78 | patch(path, options = {}) { 79 | return this.request(path, 'PATCH', options); 80 | } 81 | 82 | resolveUrl(path, variables = {}) { 83 | if (path.toLowerCase().startsWith('http://') 84 | || path.toLowerCase().startsWith('https://') 85 | || path.startsWith('//')) { 86 | return path; 87 | } 88 | 89 | const baseUrl = this.baseUrl.replace(/\/+$/g, ''); 90 | let fullUrl = ''; 91 | 92 | if (path.startsWith('/')) { 93 | const rootPos = baseUrl.indexOf('/', baseUrl.indexOf('//') + 2); 94 | fullUrl = baseUrl.substr(0, rootPos === -1 ? undefined : rootPos) + path; 95 | } else { 96 | fullUrl = `${baseUrl}/${path}`; 97 | } 98 | 99 | fullUrl = fullUrl.replace(/\{(\w+)\}/ig, (match, group) => { 100 | if (!variables[group]) throw new Error(`Unknown path variable '${group}'.`); 101 | return encodeURIComponent(variables[group]); 102 | }); 103 | 104 | return fullUrl; 105 | } 106 | } 107 | 108 | export const query = () => request => { 109 | if (request.options.query) { 110 | const queryString = stringify(request.options.query); 111 | if (request.url.indexOf('?') === -1) { 112 | request.url = request.url.concat('?'); 113 | } 114 | if (request.url.endsWith('&') || request.url.endsWith('?')) { 115 | request.url = request.url.concat(queryString); 116 | } else { 117 | request.url = request.url.concat('&', queryString); 118 | } 119 | } 120 | }; 121 | 122 | export const form = () => request => { 123 | if (request.options.form) { 124 | request.options.body = stringify(request.options.form); 125 | request.options.headers['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8'; 126 | } 127 | }; 128 | 129 | export const json = () => request => { 130 | if (request.options.json) { 131 | request.options.body = JSON.stringify(request.options.json); 132 | request.options.headers['Content-Type'] = 'application/json'; 133 | } 134 | request.options.headers.Accept = 'application/json'; 135 | 136 | return response => { 137 | const contentType = response.headers.get('Content-Type') || ''; 138 | if (contentType.indexOf('json') === -1) return response; 139 | return response.json().then(json => (response.jsonData = json, response)); 140 | }; 141 | }; 142 | 143 | export const header = headers => request => { 144 | request.options.headers = { ...request.options.headers, ...headers }; 145 | }; 146 | 147 | export const userAgent = ua => request => { 148 | const uaSegments = []; 149 | Object.keys(ua).forEach(key => uaSegments.push(`${key}/${ua[key]}`)); 150 | request.options.headers['User-Agent'] = uaSegments.join(' '); 151 | }; 152 | 153 | export const credentials = credentials => request => { 154 | request.options.credentials = credentials; 155 | }; 156 | 157 | export const timeout = globalTimeout => request => { 158 | const ms = parseInt(request.options.timeout || globalTimeout, 10); 159 | 160 | if (ms) { 161 | const fetchRequest = request.fetch; 162 | const abort = new Promise((resolve, reject) => setTimeout(reject, ms, 'request timeout!')); 163 | 164 | request.fetch = (url, options) => Promise.race([fetchRequest(url, options), abort]); 165 | } 166 | }; 167 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Fetch Http Client 2 | 3 | [![GitHub license](https://img.shields.io/badge/license-MIT-blue.svg)](https://raw.githubusercontent.com/starlight36/fetch-http-client/master/LICENSE) [![npm version](https://badge.fury.io/js/fetch-http-client.svg)](https://badge.fury.io/js/fetch-http-client) [![Build Status](https://travis-ci.org/starlight36/fetch-http-client.svg?branch=master)](https://travis-ci.org/starlight36/fetch-http-client) [![Coverage Status](https://coveralls.io/repos/github/starlight36/fetch-http-client/badge.svg)](https://coveralls.io/github/starlight36/fetch-http-client) 4 | 5 | A http client wrapper for [Fetch API](https://github.com/whatwg/fetch) with middleware support. 6 | 7 | # Introduction 8 | 9 | Fetch API is a elegant way to access HTTP resources. I used it in my React/ReactNative project as the default network layer. But it still has some inconvenience to use. For example, every request should carry the access token in HTTP request headers, ervery request error should be logged to console etc. 10 | 11 | If Fetch API support middleware, everything can be elegantly fixed. Both [fetch-plus](https://github.com/RickWong/fetch-plus) and [http-client](https://github.com/mjackson/http-client) provided the middleware support, but if you need some asynchronous pre-request opreation, they could not suppport elegantly. 12 | 13 | So this project is another choice to use Fetch API with middleware support, it's quite simple and powerful. 14 | 15 | # Installation 16 | 17 | ```shell 18 | npm install fetch-http-client --save 19 | ``` 20 | 21 | # Usage 22 | 23 | ## Import 24 | 25 | ```js 26 | import FetchHttpClient, { json } from 'fetch-http-client'; 27 | ``` 28 | 29 | ## Quick start 30 | 31 | ```js 32 | // Create a new client object. 33 | const client = new FetchHttpClient('http://api.example.com/endpoint'); 34 | 35 | // Add access token 36 | client.addMiddleware(request => { 37 | request.options.headers['X-Access-Token'] = 'secret'; 38 | }); 39 | 40 | // Add json support 41 | client.addMiddleware(json()); 42 | 43 | // Add Logging 44 | client.addMiddleware(request => response => { 45 | console.log(request, response); 46 | }); 47 | 48 | // Fire request. 49 | client.get('test').then(response => console.log(response.jsonData)); 50 | 51 | // Path variables support. 52 | client.get('users/{id}', { uriParams: { id: 1 } }).then(response => console.log(response.jsonData)); 53 | ``` 54 | 55 | ## Asynchronous pre-request middleware 56 | 57 | if your access token is stored in a asynchronous storage, it should be fetch before every request, you can use such kind of middleware: 58 | 59 | ```js 60 | // Add access token asynchronously 61 | client.addMiddleware(request => { 62 | return AsynchronousStorage.fetch('accessToken').then(token => { 63 | request.options.headers['X-Access-Token'] = token; 64 | return request; 65 | }); 66 | }); 67 | ``` 68 | 69 | That means your middleware could return a `Promise` object and the real request opreate will be issued after the asynchronous method finished. 70 | 71 | **NEVER forget returning the request object after you handled the result!** 72 | 73 | # API 74 | 75 | ## FetchHttpClient 76 | 77 | ```js 78 | new FetchHttpClient(baseUrl:string); 79 | ``` 80 | 81 | ### fetch 82 | 83 | `fetch` method can been used the same as Fetch API. 84 | 85 | ``` 86 | instance.fetch(uri:string[, options: object]) 87 | ``` 88 | 89 | ### request 90 | 91 | Convenience way to issue a request with specific verb. 92 | 93 | ``` 94 | instance.request(uri:string, method:string[, options: object]) 95 | ``` 96 | 97 | ### get 98 | 99 | Convenience way to issue a GET request. 100 | 101 | ``` 102 | instance.get(uri:string[, options: object]) 103 | ``` 104 | 105 | ### post 106 | 107 | Convenience way to issue a POST request. 108 | 109 | ``` 110 | instance.post(uri:string[, options: object]) 111 | ``` 112 | 113 | ### put 114 | 115 | Convenience way to issue a PUT request. 116 | 117 | ``` 118 | instance.put(uri:string[, options: object]) 119 | ``` 120 | 121 | ### delete 122 | 123 | Convenience way to issue a DELETE request. 124 | 125 | ``` 126 | instance.delete(uri:string[, options: object]) 127 | ``` 128 | 129 | ### patch 130 | 131 | Convenience way to issue a PATCH request. 132 | 133 | ``` 134 | instance.patch(uri:string[, options: object]) 135 | ``` 136 | 137 | ## Build-in middlewares 138 | 139 | ### query 140 | 141 | This middleware could add the ability to append object value to query string: 142 | 143 | ```js 144 | // Add query middleware 145 | client.addMiddleware(query()); 146 | 147 | // Request 148 | client.get('test', { 149 | query: { 150 | foo: 'FOO', 151 | bar: 'BAR', 152 | }, 153 | }); 154 | ``` 155 | 156 | It will request to `http://api.example.com/endpoint/test?foo=FOO&bar=BAR`. 157 | 158 | ### form 159 | 160 | Like `query`, this could be used to handle post form values. 161 | 162 | ```js 163 | // Add form middleware 164 | client.addMiddleware(form()); 165 | 166 | // Request 167 | client.post('test', { 168 | form: { 169 | foo: 'FOO', 170 | bar: 'BAR', 171 | }, 172 | }); 173 | ``` 174 | 175 | ### header 176 | 177 | A convenience middleware to add headers to request. 178 | 179 | ```js 180 | // Add header middleware 181 | client.addMiddleware(header({ 182 | 'X-Request-By': 'FetchHttpClient', 183 | })); 184 | 185 | ``` 186 | 187 | ### userAgent 188 | 189 | A convenience middleware to set User-Agent to headers. 190 | 191 | ```js 192 | // Add header middleware 193 | client.addMiddleware(userAgent({ 194 | 'Client': '1.1', 195 | })); 196 | 197 | ``` 198 | 199 | ### json 200 | 201 | Convert object to request and parse from response. 202 | 203 | ```js 204 | // Add json middleware 205 | client.addMiddleware(json()); 206 | 207 | // Request 208 | client.post('add', { 209 | json: { 210 | foo: 'FOO', 211 | }, 212 | }).then(response => { 213 | console.log(response.jsonData); 214 | }); 215 | ``` 216 | 217 | ### timeout 218 | 219 | Set timeout options to fetch. 220 | 221 | ```js 222 | // global timeout option 223 | client.addMiddleware(timeout(1000)); 224 | 225 | // Request timeout option priority global timeout option 226 | client.get('test', { 227 | timeout: 2000, // If you not add timeout middleware, it will not take effect 228 | }); 229 | ``` 230 | 231 | ### credentials 232 | 233 | Set credentials options to fetch. If you want to automatically send cookies for the current domain, use this middleware and config it as `same-origin`. 234 | 235 | ```js 236 | // Add credentials middleware 237 | client.addMiddleware(credentials('same-origin')); 238 | ``` 239 | 240 | # Feedback 241 | 242 | If you have any questions, use [Issues](https://github.com/starlight36/fetch-http-client/issues). 243 | 244 | Sina Weibo: [@starlight36](http://weibo.com/starlight36) 245 | 246 | # License 247 | 248 | MIT Licence. 249 | 250 | 251 | 252 | 253 | -------------------------------------------------------------------------------- /test/test.js: -------------------------------------------------------------------------------- 1 | import assert from 'assert'; 2 | import FetchHttpClient, { 3 | query, 4 | form, 5 | json, 6 | header, 7 | userAgent, 8 | credentials, 9 | timeout, 10 | } from '../modules'; 11 | 12 | describe('FetchHttpClient', () => { 13 | it('should be a class.', () => { 14 | assert.notEqual(FetchHttpClient, null); 15 | assert(typeof FetchHttpClient === 'function'); 16 | }); 17 | 18 | it('can be add and remove middleware.', () => { 19 | const middleware = () => null; 20 | const client = new FetchHttpClient(); 21 | client.addMiddleware(middleware).removeMiddleware(middleware); 22 | }); 23 | 24 | it('can be fetch a url, pre/post processed with middlewares.', () => { 25 | global.fetch = () => Promise.resolve({ status: 200 }); 26 | return new FetchHttpClient('http://mydomain.com') 27 | .addMiddleware(request => { 28 | assert.equal(request.url, 'http://mydomain.com/test/1'); 29 | Promise.resolve('dumy-token') 30 | .then(token => (request.options.headers.Token = token, request)); 31 | }) 32 | .addMiddleware(request => assert.equal(request.options.headers.Token, 'dumy-token')) 33 | .addMiddleware(() => response => (response.status1 = response.status, response)) 34 | .fetch('/test/{id}', { method: 'GET', uriParams: { id: 1 } }) 35 | .then(response => { 36 | assert.equal(response.status, 200); 37 | assert.equal(response.status1, 200); 38 | }); 39 | }); 40 | 41 | it('can request url.', () => { 42 | global.fetch = () => Promise.resolve({ status: 200 }); 43 | return new FetchHttpClient('http://mydomain.com') 44 | .request('/test', 'GET') 45 | .then(response => assert.equal(response.status, 200)); 46 | }); 47 | 48 | it('can request url via get.', () => { 49 | global.fetch = () => Promise.resolve({ status: 200 }); 50 | return new FetchHttpClient('http://mydomain.com') 51 | .get('/test').then(response => assert.equal(response.status, 200)); 52 | }); 53 | 54 | it('can request url via post.', () => { 55 | global.fetch = () => Promise.resolve({ status: 200 }); 56 | return new FetchHttpClient('http://mydomain.com') 57 | .post('/test').then(response => assert.equal(response.status, 200)); 58 | }); 59 | 60 | it('can request url via put.', () => { 61 | global.fetch = () => Promise.resolve({ status: 200 }); 62 | return new FetchHttpClient('http://mydomain.com') 63 | .put('/test').then(response => assert.equal(response.status, 200)); 64 | }); 65 | 66 | it('can request url via delete.', () => { 67 | global.fetch = () => Promise.resolve({ status: 200 }); 68 | return new FetchHttpClient('http://mydomain.com') 69 | .delete('/test').then(response => assert.equal(response.status, 200)); 70 | }); 71 | 72 | it('can request url via patch.', () => { 73 | global.fetch = () => Promise.resolve({ status: 200 }); 74 | return new FetchHttpClient('http://mydomain.com') 75 | .patch('/test').then(response => assert.equal(response.status, 200)); 76 | }); 77 | 78 | it('can resovle a url.', () => { 79 | let client = new FetchHttpClient('http://mydomain.com'); 80 | assert.equal('http://mydomain.com/', client.resolveUrl('/')); 81 | assert.equal('http://mydomain.com/api', client.resolveUrl('/api')); 82 | assert.equal('http://mydomain.com/api', client.resolveUrl('api')); 83 | assert.equal('http://site.com/test/path', client.resolveUrl('http://site.com/test/path')); 84 | assert.equal('https://site.com/test/path', client.resolveUrl('https://site.com/test/path')); 85 | assert.equal('//site.com/test/path', client.resolveUrl('//site.com/test/path')); 86 | assert.equal('http://mydomain.com/api/1', client.resolveUrl('api/{id}', { id: 1 })); 87 | assert.equal('http://mydomain.com/api/1/test', client.resolveUrl('api/{id}/{name}', { id: 1, name: 'test' })); 88 | assert.equal('http://mydomain.com/api/%E6%B1%89%E5%AD%97', client.resolveUrl('api/{name}', { name: '汉字' })); 89 | try { 90 | client.resolveUrl('api/{unknown}'); 91 | assert.fail('Should throw exception when a unknown variable in path.'); 92 | } catch (ex) { 93 | assert.equal('Unknown path variable \'unknown\'.', ex.message); 94 | } 95 | client = new FetchHttpClient('http://mydomain.com/api'); 96 | assert.equal('http://mydomain.com/test', client.resolveUrl('/test')); 97 | assert.equal('http://mydomain.com/api/test', client.resolveUrl('test')); 98 | client = new FetchHttpClient('//mydomain.com/api'); 99 | assert.equal('//mydomain.com/test', client.resolveUrl('/test')); 100 | assert.equal('//mydomain.com/api/test', client.resolveUrl('test')); 101 | }); 102 | }); 103 | 104 | describe('Middleware query', () => { 105 | it('should create query string.', () => { 106 | let request = { 107 | url: '/test', 108 | options: { 109 | query: { 110 | key: 'value', 111 | }, 112 | }, 113 | }; 114 | query()(request); 115 | assert.equal(request.url, '/test?key=value'); 116 | 117 | request = { 118 | url: '/test?', 119 | options: { 120 | query: { 121 | key: 'value', 122 | }, 123 | }, 124 | }; 125 | query()(request); 126 | assert.equal(request.url, '/test?key=value'); 127 | 128 | request = { 129 | url: '/test?id=1', 130 | options: { 131 | query: { 132 | key: 'value', 133 | }, 134 | }, 135 | }; 136 | query()(request); 137 | assert.equal(request.url, '/test?id=1&key=value'); 138 | 139 | request = { 140 | url: '/test?id=1&', 141 | options: { 142 | query: { 143 | key: 'value', 144 | }, 145 | }, 146 | }; 147 | query()(request); 148 | assert.equal(request.url, '/test?id=1&key=value'); 149 | }); 150 | }); 151 | 152 | describe('Middleware form', () => { 153 | it('should create form request.', () => { 154 | const request = { 155 | options: { 156 | headers: {}, 157 | form: { 158 | key: 'value', 159 | }, 160 | }, 161 | }; 162 | form()(request); 163 | assert.equal(request.options.body, 'key=value'); 164 | assert.equal(request.options.headers['Content-Type'] 165 | , 'application/x-www-form-urlencoded;charset=UTF-8'); 166 | }); 167 | }); 168 | 169 | describe('Middleware json', done => { 170 | it('should handle json request and response.', () => { 171 | const request = { 172 | options: { 173 | headers: {}, 174 | json: { 175 | key: 'value', 176 | }, 177 | }, 178 | }; 179 | 180 | const response = { 181 | headers: { 182 | get: key => { 183 | assert.equal(key, 'Content-Type'); 184 | return 'application/json'; 185 | }, 186 | }, 187 | json: () => Promise.resolve(({ key: 'value' })), 188 | }; 189 | 190 | json()(request)(response).then(response => { 191 | assert.equal(response.jsonData, { key: 'value' }); 192 | done(); 193 | }); 194 | assert.equal(request.options.body, '{"key":"value"}'); 195 | assert.equal(request.options.headers['Content-Type'], 'application/json'); 196 | assert.equal(request.options.headers.Accept, 'application/json'); 197 | }); 198 | 199 | it('should handle request without body and response.', () => { 200 | const request = { 201 | options: { 202 | headers: {}, 203 | }, 204 | }; 205 | 206 | const response = { 207 | headers: { 208 | get: key => { 209 | assert.equal(key, 'Content-Type'); 210 | return 'application/json'; 211 | }, 212 | }, 213 | json: () => Promise.resolve(({ key: 'value' })), 214 | }; 215 | 216 | json()(request)(response).then(response => { 217 | assert.equal(response.jsonData, { key: 'value' }); 218 | done(); 219 | }); 220 | assert.equal(request.options.headers.Accept, 'application/json'); 221 | }); 222 | }); 223 | 224 | 225 | describe('Middleware header', () => { 226 | it('should create headers on request.', () => { 227 | const request = { 228 | options: { 229 | headers: {}, 230 | }, 231 | }; 232 | header({ 'X-Test': 'test' })(request); 233 | assert.equal(request.options.headers['X-Test'], 'test'); 234 | }); 235 | }); 236 | 237 | describe('Middleware userAgent', () => { 238 | it('should userAgent headers on request.', () => { 239 | const request = { 240 | options: { 241 | headers: {}, 242 | }, 243 | }; 244 | userAgent({ Test: 'test', Test2: 'test2' })(request); 245 | assert.equal(request.options.headers['User-Agent'], 'Test/test Test2/test2'); 246 | }); 247 | }); 248 | 249 | describe('Middleware credentials', () => { 250 | it('should set credentials options on request.', () => { 251 | const request = { 252 | options: {}, 253 | }; 254 | credentials('same-origin')(request); 255 | assert.equal(request.options.credentials, 'same-origin'); 256 | }); 257 | }); 258 | 259 | describe('Middleware timeout', () => { 260 | it('should set timeout options on global.', () => { 261 | global.fetch = () => new Promise(resolve => { 262 | setTimeout(resolve, 1000, 'success!'); 263 | }); 264 | const client = new FetchHttpClient('http://mydomain.com'); 265 | 266 | client.addMiddleware(timeout(2000)); 267 | 268 | return client.get('/test').then(res => { 269 | assert.equal(res, 'success!'); 270 | }); 271 | }).timeout(5000); 272 | 273 | it('should set timeout options on global, with timeout.', () => { 274 | global.fetch = () => new Promise(resolve => { 275 | setTimeout(resolve, 2000, 'success!'); 276 | }); 277 | const client = new FetchHttpClient('http://mydomain.com'); 278 | 279 | client.addMiddleware(timeout(1000)); 280 | 281 | return client.get('/test').catch((err) => { 282 | assert.equal(err, 'request timeout!'); 283 | }); 284 | }).timeout(5000); 285 | 286 | it('should set timeout options on request method.', () => { 287 | global.fetch = () => new Promise(resolve => { 288 | setTimeout(resolve, 2000, 'success!'); 289 | }); 290 | const client = new FetchHttpClient('http://mydomain.com'); 291 | 292 | client.addMiddleware(timeout(1000)); 293 | 294 | return client.get('/test', { 295 | timeout: 3000, 296 | }).then((res) => { 297 | assert.equal(res, 'success!'); 298 | }); 299 | }).timeout(5000); 300 | }); 301 | 302 | --------------------------------------------------------------------------------