├── .editorconfig ├── .github └── workflows │ ├── compressed-size.yml │ └── main.yml ├── .gitignore ├── .prettierignore ├── CONTRIBUTING.md ├── LICENSE ├── README.md ├── mod.ts ├── package-lock.json ├── package.json ├── src └── index.js ├── test ├── fixtures │ ├── example.json.txt │ └── example.txt └── index.test.js └── tsconfig.json /.editorconfig: -------------------------------------------------------------------------------- 1 | root = true 2 | 3 | [*] 4 | indent_style = tab 5 | end_of_line = lf 6 | charset = utf-8 7 | trim_trailing_whitespace = true 8 | insert_final_newline = true 9 | 10 | [{*.json,*.md,.*rc,*.yml,*.txt}] 11 | indent_style = space 12 | indent_size = 2 13 | -------------------------------------------------------------------------------- /.github/workflows/compressed-size.yml: -------------------------------------------------------------------------------- 1 | name: Compressed Size 2 | 3 | on: [pull_request] 4 | 5 | jobs: 6 | build: 7 | runs-on: ubuntu-latest 8 | 9 | steps: 10 | - uses: actions/checkout@v2 11 | - uses: preactjs/compressed-size-action@v1 12 | with: 13 | repo-token: '${{ secrets.GITHUB_TOKEN }}' 14 | -------------------------------------------------------------------------------- /.github/workflows/main.yml: -------------------------------------------------------------------------------- 1 | name: CI 2 | 3 | on: 4 | push: 5 | branches: 6 | - master 7 | pull_request: 8 | branches: 9 | - master 10 | 11 | jobs: 12 | build: 13 | runs-on: ubuntu-latest 14 | 15 | steps: 16 | - uses: actions/checkout@v1 17 | - uses: actions/setup-node@v1 18 | with: 19 | node-version: 12 20 | - name: npm install, build, and test 21 | run: | 22 | npm ci 23 | npm run build --if-present 24 | npm test 25 | env: 26 | CI: true 27 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | node_modules 2 | dist 3 | coverage 4 | -------------------------------------------------------------------------------- /.prettierignore: -------------------------------------------------------------------------------- 1 | node_modules 2 | package-lock.json 3 | dist 4 | coverage 5 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # How to Contribute 2 | 3 | We'd love to accept your patches and contributions to this project. There are 4 | just a few small guidelines you need to follow. 5 | 6 | ## Contributor License Agreement 7 | 8 | Contributions to this project must be accompanied by a Contributor License 9 | Agreement. You (or your employer) retain the copyright to your contribution, 10 | this simply gives us permission to use and redistribute your contributions as 11 | part of the project. Head over to to see 12 | your current agreements on file or to sign a new one. 13 | 14 | You generally only need to submit a CLA once, so if you've already submitted one 15 | (even if it was for a different project), you probably don't need to do it 16 | again. 17 | 18 | ## Code reviews 19 | 20 | All submissions, including submissions by project members, require review. We 21 | use GitHub pull requests for this purpose. Consult 22 | [GitHub Help](https://help.github.com/articles/about-pull-requests/) for more 23 | information on using pull requests. 24 | 25 | ## Community Guidelines 26 | 27 | This project follows [Google's Open Source Community 28 | Guidelines](https://opensource.google.com/conduct/). 29 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # redaxios 2 | 3 | [Axios] has a great API that developers love. Redaxios provides that API in **800 bytes**, using native `fetch()`. 4 | 5 | For those searching for ways to shave a few kilobytes off of their bundles, that's less than 1/5th of the size. This is made possible by using the browser's native [Fetch API][fetch], which is [supported in all modern browsers](https://caniuse.com/#feat=fetch) and polyfilled by most tools including Next.js, Create React App and Preact CLI. 6 | 7 | ### Can I just use Axios? 8 | 9 | Yes! Axios is an excellent module and you should use it! Redaxios exists so that you can use that same API in cases where it's difficult to justify the dependency. Instead of having to choose between Axios and Fetch, Redaxios provides a middle-ground between the two. 10 | 11 | [axios]: https://github.com/axios/axios 12 | [fetch]: https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch 13 | 14 | ### Usage 15 | 16 | ```js 17 | import axios from 'redaxios'; 18 | // use as you would normally 19 | ``` 20 | 21 | Refer to the [Axios Documentation](https://github.com/axios/axios#axios-api). 22 | -------------------------------------------------------------------------------- /mod.ts: -------------------------------------------------------------------------------- 1 | export { default } from './src/index.js' 2 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "redaxios", 3 | "version": "0.5.1", 4 | "description": "The API from Axios, as a tiny abstraction over Fetch.", 5 | "source": "src/index.js", 6 | "main": "dist/redaxios.js", 7 | "umd:main": "dist/redaxios.umd.js", 8 | "module": "dist/redaxios.module.js", 9 | "types": "dist/index.d.ts", 10 | "scripts": { 11 | "build": "microbundle && tsc", 12 | "test": "npm run format:check && eslint src test && karmatic", 13 | "release": "npm run build && npm t && git commit -am \"$npm_package_version\" && git tag $npm_package_version && git push && git push --tags && npm publish", 14 | "format": "prettier --write './**/*.{js,json,yml,md}'", 15 | "format:check": "prettier --check './**/*.{js,json,yml,md}'" 16 | }, 17 | "files": [ 18 | "dist", 19 | "src" 20 | ], 21 | "eslintConfig": { 22 | "extends": [ 23 | "developit", 24 | "prettier" 25 | ], 26 | "rules": { 27 | "jest/no-jasmine-globals": "off" 28 | } 29 | }, 30 | "prettier": { 31 | "arrowParens": "always", 32 | "trailingComma": "none", 33 | "singleQuote": true, 34 | "endOfLine": "lf", 35 | "useTabs": true, 36 | "printWidth": 120, 37 | "overrides": [ 38 | { 39 | "files": "**/*.json", 40 | "options": { 41 | "parser": "json-stringify", 42 | "useTabs": false, 43 | "tabWidth": 2 44 | } 45 | } 46 | ] 47 | }, 48 | "repository": "developit/redaxios", 49 | "keywords": [ 50 | "axios", 51 | "fetch" 52 | ], 53 | "author": "Jason Miller ", 54 | "license": "Apache-2.0", 55 | "homepage": "https://github.com/developit/redaxios", 56 | "devDependencies": { 57 | "@types/jest": "^26.0.4", 58 | "core-js": "2.6.11", 59 | "eslint": "^7.5.0", 60 | "eslint-config-developit": "^1.2.0", 61 | "eslint-config-prettier": "6.11.0", 62 | "file-loader": "^5.0.2", 63 | "isomorphic-fetch": "^2.2.1", 64 | "karmatic": "^2.1.0", 65 | "microbundle": "^0.11.0", 66 | "npm-merge-driver-install": "^1.1.1", 67 | "prettier": "2.0.5", 68 | "typescript": "3.9.7", 69 | "webpack": "^4.41.5" 70 | } 71 | } 72 | -------------------------------------------------------------------------------- /src/index.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2018 Google Inc. All Rights Reserved. 3 | * Licensed under the Apache License, Version 2.0 (the "License"); 4 | * you may not use this file except in compliance with the License. 5 | * You may obtain a copy of the License at 6 | * http://www.apache.org/licenses/LICENSE-2.0 7 | * Unless required by applicable law or agreed to in writing, software 8 | * distributed under the License is distributed on an "AS IS" BASIS, 9 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 10 | * See the License for the specific language governing permissions and 11 | * limitations under the License. 12 | */ 13 | 14 | /** 15 | * @public 16 | * @typedef Options 17 | * @property {string} [url] the URL to request 18 | * @property {'get'|'post'|'put'|'patch'|'delete'|'options'|'head'|'GET'|'POST'|'PUT'|'PATCH'|'DELETE'|'OPTIONS'|'HEAD'} [method="get"] HTTP method, case-insensitive 19 | * @property {RequestHeaders} [headers] Request headers 20 | * @property {FormData|string|object} [body] a body, optionally encoded, to send 21 | * @property {'text'|'json'|'stream'|'blob'|'arrayBuffer'|'formData'|'stream'} [responseType="json"] An encoding to use for the response 22 | * @property {Record|URLSearchParams} [params] querystring parameters 23 | * @property {(params: Options['params']) => string} [paramsSerializer] custom function to stringify querystring parameters 24 | * @property {boolean} [withCredentials] Send the request with credentials like cookies 25 | * @property {string} [auth] Authorization header value to send with the request 26 | * @property {string} [xsrfCookieName] Pass an Cross-site Request Forgery prevention cookie value as a header defined by `xsrfHeaderName` 27 | * @property {string} [xsrfHeaderName] The name of a header to use for passing XSRF cookies 28 | * @property {(status: number) => boolean} [validateStatus] Override status code handling (default: 200-399 is a success) 29 | * @property {Array<(body: any, headers?: RequestHeaders) => any?>} [transformRequest] An array of transformations to apply to the outgoing request 30 | * @property {string} [baseURL] a base URL from which to resolve all URLs 31 | * @property {typeof window.fetch} [fetch] Custom window.fetch implementation 32 | * @property {any} [data] 33 | */ 34 | 35 | /** 36 | * @public 37 | * @typedef RequestHeaders 38 | * @type {{[name: string]: string} | Headers} 39 | */ 40 | 41 | /** 42 | * @public 43 | * @template T 44 | * @typedef Response 45 | * @property {number} status 46 | * @property {string} statusText 47 | * @property {Options} config the request configuration 48 | * @property {T} data the decoded response body 49 | * @property {Headers} headers 50 | * @property {boolean} redirect 51 | * @property {string} url 52 | * @property {ResponseType} type 53 | * @property {ReadableStream | null} body 54 | * @property {boolean} bodyUsed 55 | */ 56 | 57 | /** 58 | * @typedef BodylessMethod 59 | * @type {(url: string, config?: Options) => Promise>} 60 | */ 61 | 62 | /** 63 | * @typedef BodyMethod 64 | * @type {(url: string, body?: any, config?: Options) => Promise>} 65 | */ 66 | 67 | /** 68 | * @public 69 | * @param {Options} [defaults = {}] 70 | * @returns {redaxios} 71 | */ 72 | function create(defaults) { 73 | defaults = defaults || {}; 74 | 75 | /** 76 | * @public 77 | * @template T 78 | * @type {((config?: Options) => Promise>) | ((url: string, config?: Options) => Promise>)} 79 | */ 80 | redaxios.request = redaxios; 81 | 82 | /** @public @type {BodylessMethod} */ 83 | redaxios.get = (url, config) => redaxios(url, config, 'get'); 84 | 85 | /** @public @type {BodylessMethod} */ 86 | redaxios.delete = (url, config) => redaxios(url, config, 'delete'); 87 | 88 | /** @public @type {BodylessMethod} */ 89 | redaxios.head = (url, config) => redaxios(url, config, 'head'); 90 | 91 | /** @public @type {BodylessMethod} */ 92 | redaxios.options = (url, config) => redaxios(url, config, 'options'); 93 | 94 | /** @public @type {BodyMethod} */ 95 | redaxios.post = (url, data, config) => redaxios(url, config, 'post', data); 96 | 97 | /** @public @type {BodyMethod} */ 98 | redaxios.put = (url, data, config) => redaxios(url, config, 'put', data); 99 | 100 | /** @public @type {BodyMethod} */ 101 | redaxios.patch = (url, data, config) => redaxios(url, config, 'patch', data); 102 | 103 | /** @public */ 104 | redaxios.all = Promise.all.bind(Promise); 105 | 106 | /** 107 | * @public 108 | * @template Args, R 109 | * @param {(...args: Args[]) => R} fn 110 | * @returns {(array: Args[]) => R} 111 | */ 112 | redaxios.spread = (fn) => /** @type {any} */ (fn.apply.bind(fn, fn)); 113 | 114 | /** 115 | * @private 116 | * @template T, U 117 | * @param {T} opts 118 | * @param {U} [overrides] 119 | * @param {boolean} [lowerCase] 120 | * @returns {{} & (T | U)} 121 | */ 122 | function deepMerge(opts, overrides, lowerCase) { 123 | let out = /** @type {any} */ ({}), 124 | i; 125 | if (Array.isArray(opts)) { 126 | // @ts-ignore 127 | return opts.concat(overrides); 128 | } 129 | for (i in opts) { 130 | const key = lowerCase ? i.toLowerCase() : i; 131 | out[key] = opts[i]; 132 | } 133 | for (i in overrides) { 134 | const key = lowerCase ? i.toLowerCase() : i; 135 | const value = /** @type {any} */ (overrides)[i]; 136 | out[key] = key in out && typeof value == 'object' ? deepMerge(out[key], value, key == 'headers') : value; 137 | } 138 | return out; 139 | } 140 | 141 | /** 142 | * Issues a request. 143 | * @public 144 | * @template T 145 | * @param {string | Options} urlOrConfig 146 | * @param {Options} [config = {}] 147 | * @param {any} [_method] (internal) 148 | * @param {any} [data] (internal) 149 | * @param {never} [_undefined] (internal) 150 | * @returns {Promise>} 151 | */ 152 | function redaxios(urlOrConfig, config, _method, data, _undefined) { 153 | let url = /** @type {string} */ (typeof urlOrConfig != 'string' ? (config = urlOrConfig).url : urlOrConfig); 154 | 155 | const response = /** @type {Response} */ ({ config }); 156 | 157 | /** @type {Options} */ 158 | const options = deepMerge(defaults, config); 159 | 160 | /** @type {RequestHeaders} */ 161 | const customHeaders = {}; 162 | 163 | data = data || options.data; 164 | 165 | (options.transformRequest || []).map((f) => { 166 | data = f(data, options.headers) || data; 167 | }); 168 | 169 | if (options.auth) { 170 | customHeaders.authorization = options.auth; 171 | } 172 | 173 | if (data && typeof data === 'object' && typeof data.append !== 'function' && typeof data.text !== 'function') { 174 | data = JSON.stringify(data); 175 | customHeaders['content-type'] = 'application/json'; 176 | } 177 | 178 | try { 179 | // @ts-ignore providing the cookie name without header name is nonsensical anyway 180 | customHeaders[options.xsrfHeaderName] = decodeURIComponent( 181 | // @ts-ignore accessing match()[2] throws for no match, which is intentional 182 | document.cookie.match(RegExp('(^|; )' + options.xsrfCookieName + '=([^;]*)'))[2] 183 | ); 184 | } catch (e) {} 185 | 186 | if (options.baseURL) { 187 | url = url.replace(/^(?!.*\/\/)\/?/, options.baseURL + '/'); 188 | } 189 | 190 | if (options.params) { 191 | url += 192 | (~url.indexOf('?') ? '&' : '?') + 193 | (options.paramsSerializer ? options.paramsSerializer(options.params) : new URLSearchParams(options.params)); 194 | } 195 | 196 | const fetchFunc = options.fetch || fetch; 197 | 198 | return fetchFunc(url, { 199 | method: (_method || options.method || 'get').toUpperCase(), 200 | body: data, 201 | headers: deepMerge(options.headers, customHeaders, true), 202 | credentials: options.withCredentials ? 'include' : _undefined 203 | }).then((res) => { 204 | for (const i in res) { 205 | if (typeof res[i] != 'function') response[i] = res[i]; 206 | } 207 | 208 | if (options.responseType == 'stream') { 209 | response.data = res.body; 210 | return response; 211 | } 212 | 213 | return res[options.responseType || 'text']() 214 | .then((data) => { 215 | response.data = data; 216 | // its okay if this fails: response.data will be the unparsed value: 217 | response.data = JSON.parse(data); 218 | }) 219 | .catch(Object) 220 | .then(() => { 221 | const ok = options.validateStatus ? options.validateStatus(res.status) : res.ok; 222 | return ok ? response : Promise.reject(response); 223 | }); 224 | }); 225 | } 226 | 227 | /** 228 | * @public 229 | * @type {AbortController} 230 | */ 231 | redaxios.CancelToken = /** @type {any} */ (typeof AbortController == 'function' ? AbortController : Object); 232 | 233 | /** 234 | * @public 235 | * @type {Options} 236 | */ 237 | redaxios.defaults = defaults; 238 | 239 | /** 240 | * @public 241 | */ 242 | redaxios.create = create; 243 | 244 | return redaxios; 245 | } 246 | 247 | export default create(); 248 | -------------------------------------------------------------------------------- /test/fixtures/example.json.txt: -------------------------------------------------------------------------------- 1 | { 2 | "hello": "world" 3 | } -------------------------------------------------------------------------------- /test/fixtures/example.txt: -------------------------------------------------------------------------------- 1 | some example content -------------------------------------------------------------------------------- /test/index.test.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2018 Google Inc. All Rights Reserved. 3 | * Licensed under the Apache License, Version 2.0 (the "License"); 4 | * you may not use this file except in compliance with the License. 5 | * You may obtain a copy of the License at 6 | * http://www.apache.org/licenses/LICENSE-2.0 7 | * Unless required by applicable law or agreed to in writing, software 8 | * distributed under the License is distributed on an "AS IS" BASIS, 9 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 10 | * See the License for the specific language governing permissions and 11 | * limitations under the License. 12 | */ 13 | 14 | // @ts-ignore 15 | import textExample from 'file-loader!./fixtures/example.txt'; 16 | // @ts-ignore 17 | import jsonExample from 'file-loader!./fixtures/example.json.txt'; 18 | import axios from '../src/index.js'; 19 | import fetch from 'isomorphic-fetch'; 20 | 21 | describe('redaxios', () => { 22 | describe('basic functionality', () => { 23 | it('should return text and a 200 status for a simple GET request', async () => { 24 | const req = axios(textExample); 25 | expect(req).toBeInstanceOf(Promise); 26 | const res = await req; 27 | expect(res).toBeInstanceOf(Object); 28 | expect(res.status).toEqual(200); 29 | expect(res.data).toEqual('some example content'); 30 | }); 31 | 32 | it('should return a rejected promise for 404 responses', async () => { 33 | const req = axios('/foo.txt'); 34 | expect(req).toBeInstanceOf(Promise); 35 | const spy = jasmine.createSpy(); 36 | await req.catch(spy); 37 | expect(spy).toHaveBeenCalledTimes(1); 38 | expect(spy).toHaveBeenCalledWith(jasmine.objectContaining({ status: 404 })); 39 | }); 40 | }); 41 | 42 | describe('options.responseType', () => { 43 | it('should parse responses as JSON by default', async () => { 44 | const res = await axios.get(jsonExample); 45 | expect(res.data).toEqual({ hello: 'world' }); 46 | }); 47 | 48 | it('should fall back to text for non-JSON by default', async () => { 49 | const res = await axios.get(textExample); 50 | expect(res.data).toEqual('some example content'); 51 | }); 52 | 53 | it('should force JSON for responseType:json', async () => { 54 | const res = await axios.get(jsonExample, { 55 | responseType: 'json' 56 | }); 57 | expect(res.data).toEqual({ hello: 'world' }); 58 | }); 59 | 60 | it('should fall back to undefined for failed JSON parse', async () => { 61 | const res = await axios.get(textExample, { 62 | responseType: 'json' 63 | }); 64 | expect(res.data).toEqual(undefined); 65 | }); 66 | 67 | it('should still parse JSON when responseType:text', async () => { 68 | // this is just how axios works 69 | const res = await axios.get(jsonExample, { 70 | responseType: 'text' 71 | }); 72 | expect(res.data).toEqual({ hello: 'world' }); 73 | }); 74 | }); 75 | 76 | describe('options.baseURL', () => { 77 | it('should resolve URLs relative to baseURL if provided', async () => { 78 | const oldFetch = window.fetch; 79 | try { 80 | window.fetch = jasmine 81 | .createSpy('fetch') 82 | .and.returnValue(Promise.resolve({ ok: true, status: 200, text: () => Promise.resolve('') })); 83 | const req = axios.get('/bar', { 84 | baseURL: 'http://foo' 85 | }); 86 | expect(window.fetch).toHaveBeenCalledTimes(1); 87 | expect(window.fetch).toHaveBeenCalledWith( 88 | 'http://foo/bar', 89 | jasmine.objectContaining({ 90 | method: 'GET', 91 | headers: {}, 92 | body: undefined 93 | }) 94 | ); 95 | const res = await req; 96 | expect(res.status).toEqual(200); 97 | } finally { 98 | window.fetch = oldFetch; 99 | } 100 | }); 101 | 102 | it('should resolve baseURL for relative URIs', async () => { 103 | const oldFetch = window.fetch; 104 | try { 105 | window.fetch = jasmine 106 | .createSpy('fetch') 107 | .and.returnValue(Promise.resolve({ ok: true, status: 200, text: () => Promise.resolve('') })); 108 | const req = axios.get('/bar', { 109 | baseURL: '/foo' 110 | }); 111 | expect(window.fetch).toHaveBeenCalledTimes(1); 112 | expect(window.fetch).toHaveBeenCalledWith( 113 | '/foo/bar', 114 | jasmine.objectContaining({ 115 | method: 'GET', 116 | headers: {}, 117 | body: undefined 118 | }) 119 | ); 120 | const res = await req; 121 | expect(res.status).toEqual(200); 122 | } finally { 123 | window.fetch = oldFetch; 124 | } 125 | }); 126 | }); 127 | 128 | describe('options.headers', () => { 129 | it('should merge headers case-insensitively', async () => { 130 | const oldFetch = window.fetch; 131 | try { 132 | const fetch = (window.fetch = jasmine.createSpy('fetch').and.returnValue( 133 | Promise.resolve({ 134 | ok: true, 135 | status: 200, 136 | text: () => Promise.resolve('yep') 137 | }) 138 | )); 139 | await axios('/', { headers: { 'x-foo': '2' } }); 140 | expect(fetch.calls.first().args[1].headers).toEqual({ 141 | 'x-foo': '2' 142 | }); 143 | 144 | fetch.calls.reset(); 145 | 146 | await axios('/', { headers: { 'x-foo': '2', 'X-Foo': '4' } }); 147 | expect(fetch.calls.first().args[1].headers).toEqual({ 148 | 'x-foo': '4' 149 | }); 150 | 151 | fetch.calls.reset(); 152 | 153 | const request = axios.create({ 154 | headers: { 155 | 'Base-Upper': 'base', 156 | 'base-lower': 'base' 157 | } 158 | }); 159 | await request('/'); 160 | expect(fetch.calls.first().args[1].headers).toEqual({ 161 | 'base-upper': 'base', 162 | 'base-lower': 'base' 163 | }); 164 | 165 | fetch.calls.reset(); 166 | 167 | await request('/', { 168 | headers: { 169 | 'base-upper': 'replaced', 170 | 'BASE-LOWER': 'replaced' 171 | } 172 | }); 173 | expect(fetch.calls.first().args[1].headers).toEqual({ 174 | 'base-upper': 'replaced', 175 | 'base-lower': 'replaced' 176 | }); 177 | } finally { 178 | window.fetch = oldFetch; 179 | } 180 | }); 181 | }); 182 | 183 | describe('options.body (request bodies)', () => { 184 | let oldFetch, fetchMock; 185 | beforeEach(() => { 186 | oldFetch = window.fetch; 187 | fetchMock = window.fetch = jasmine.createSpy('fetch').and.returnValue( 188 | Promise.resolve({ 189 | ok: true, 190 | status: 200, 191 | text: () => Promise.resolve('yep') 192 | }) 193 | ); 194 | }); 195 | afterEach(() => { 196 | window.fetch = oldFetch; 197 | }); 198 | 199 | it('should issue POST requests (with JSON body)', async () => { 200 | const res = await axios.post('/foo', { 201 | hello: 'world' 202 | }); 203 | expect(fetchMock).toHaveBeenCalledWith( 204 | '/foo', 205 | jasmine.objectContaining({ 206 | method: 'POST', 207 | headers: { 208 | 'content-type': 'application/json' 209 | }, 210 | body: '{"hello":"world"}' 211 | }) 212 | ); 213 | expect(res.status).toEqual(200); 214 | expect(res.data).toEqual('yep'); 215 | }); 216 | 217 | it('should issue PATCH requests (with JSON body)', async () => { 218 | const res = await axios.patch('/foo', { 219 | hello: 'world' 220 | }); 221 | expect(fetchMock).toHaveBeenCalledWith( 222 | '/foo', 223 | jasmine.objectContaining({ 224 | method: 'PATCH', 225 | headers: { 226 | 'content-type': 'application/json' 227 | }, 228 | body: '{"hello":"world"}' 229 | }) 230 | ); 231 | expect(res.status).toEqual(200); 232 | expect(res.data).toEqual('yep'); 233 | }); 234 | 235 | describe('FormData support', () => { 236 | it('should not send JSON content-type when data contains FormData', async () => { 237 | const formData = new FormData(); 238 | await axios.post('/foo', formData); 239 | expect(fetchMock).toHaveBeenCalledWith( 240 | '/foo', 241 | jasmine.objectContaining({ 242 | body: formData, 243 | headers: {} 244 | }) 245 | ); 246 | }); 247 | 248 | it('should preserve global content-type option when using FormData', async () => { 249 | const data = new FormData(); 250 | data.append('hello', 'world'); 251 | const res = await axios.post('/foo', data, { headers: { 'content-type': 'multipart/form-data' } }); 252 | expect(fetchMock).toHaveBeenCalledTimes(1); 253 | expect(fetchMock).toHaveBeenCalledWith( 254 | '/foo', 255 | jasmine.objectContaining({ 256 | method: 'POST', 257 | headers: { 258 | 'content-type': 'multipart/form-data' 259 | }, 260 | body: data 261 | }) 262 | ); 263 | expect(res.status).toEqual(200); 264 | expect(res.data).toEqual('yep'); 265 | }); 266 | }); 267 | }); 268 | 269 | describe('options.fetch', () => { 270 | it('should accept a custom fetch implementation', async () => { 271 | const req = axios.get(jsonExample, { fetch }); 272 | expect(req).toBeInstanceOf(Promise); 273 | const res = await req; 274 | expect(res).toBeInstanceOf(Object); 275 | expect(res.status).toEqual(200); 276 | expect(res.data).toEqual({ hello: 'world' }); 277 | }); 278 | }); 279 | 280 | describe('options.params & options.paramsSerializer', () => { 281 | let oldFetch, fetchMock; 282 | beforeEach(() => { 283 | oldFetch = window.fetch; 284 | fetchMock = window.fetch = jasmine.createSpy('fetch').and.returnValue(Promise.resolve()); 285 | }); 286 | 287 | afterEach(() => { 288 | window.fetch = oldFetch; 289 | }); 290 | 291 | it('should not serialize missing params', async () => { 292 | axios.get('/foo'); 293 | expect(fetchMock).toHaveBeenCalledWith('/foo', jasmine.any(Object)); 294 | }); 295 | 296 | it('should serialize numeric and boolean params', async () => { 297 | const params = { a: 1, b: true }; 298 | axios.get('/foo', { params }); 299 | expect(fetchMock).toHaveBeenCalledWith('/foo?a=1&b=true', jasmine.any(Object)); 300 | }); 301 | 302 | it('should merge params into existing url querystring', async () => { 303 | const params = { a: 1, b: true }; 304 | axios.get('/foo?c=42', { params }); 305 | expect(fetchMock).toHaveBeenCalledWith('/foo?c=42&a=1&b=true', jasmine.any(Object)); 306 | }); 307 | 308 | it('should accept a URLSearchParams instance', async () => { 309 | const params = new URLSearchParams({ d: 'test' }); 310 | axios.get('/foo', { params }); 311 | expect(fetchMock).toHaveBeenCalledWith('/foo?d=test', jasmine.any(Object)); 312 | }); 313 | 314 | it('should accept a custom paramsSerializer function', async () => { 315 | const params = { a: 1, b: true }; 316 | const paramsSerializer = (params) => 'e=iamthelaw'; 317 | axios.get('/foo', { params, paramsSerializer }); 318 | expect(fetchMock).toHaveBeenCalledWith('/foo?e=iamthelaw', jasmine.any(Object)); 319 | }); 320 | }); 321 | 322 | describe('static helpers', () => { 323 | it(`#all should work`, async () => { 324 | const result = await axios.all([Promise.resolve('hello'), Promise.resolve('world')]); 325 | 326 | expect(result).toEqual(['hello', 'world']); 327 | }); 328 | 329 | it(`#spread should work`, async () => { 330 | const result = await axios.all([Promise.resolve('hello'), Promise.resolve('world')]).then( 331 | axios.spread((item1, item2) => { 332 | return `${item1} ${item2}`; 333 | }) 334 | ); 335 | 336 | expect(result).toEqual('hello world'); 337 | }); 338 | }); 339 | }); 340 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "target": "ESNext", 4 | "module": "ESNext", 5 | "lib": [ 6 | "DOM", 7 | "ESNext" 8 | ], 9 | "allowJs": true, 10 | "checkJs": true, 11 | "declaration": true, 12 | "emitDeclarationOnly": true, 13 | "declarationMap": true, 14 | "declarationDir": "./dist", 15 | "noEmit": false, 16 | "strict": true, 17 | "suppressImplicitAnyIndexErrors": true, 18 | "noImplicitThis": false, 19 | "moduleResolution": "node", 20 | "esModuleInterop": true, 21 | "skipLibCheck": true, 22 | "forceConsistentCasingInFileNames": true 23 | }, 24 | "include": [ 25 | "src" 26 | ] 27 | } 28 | --------------------------------------------------------------------------------