├── .npmignore ├── .gitignore ├── .travis.yml ├── test ├── .eslintrc.json └── EndPoint.js ├── .babelrc ├── .eslintrc.json ├── src ├── SuperApi.js └── EndPoint.js ├── package.json ├── README.md └── LICENSE.txt /.npmignore: -------------------------------------------------------------------------------- 1 | src/ 2 | .tmp 3 | .idea 4 | coverage 5 | npm-debug.log -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | lib 2 | node_modules 3 | .tmp 4 | .idea 5 | coverage 6 | npm-debug.log -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: node_js 2 | node_js: 3 | - "6" 4 | after_success: 5 | - npm run coveralls -------------------------------------------------------------------------------- /test/.eslintrc.json: -------------------------------------------------------------------------------- 1 | { 2 | "plugins": [ 3 | "mocha" 4 | ], 5 | "env": { 6 | "mocha": true 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /.babelrc: -------------------------------------------------------------------------------- 1 | { 2 | "presets": [ 3 | "es2015" 4 | ], 5 | "plugins": [ 6 | "transform-object-rest-spread" 7 | ] 8 | } 9 | -------------------------------------------------------------------------------- /.eslintrc.json: -------------------------------------------------------------------------------- 1 | { 2 | "parser": "babel-eslint", 3 | "extends": "eslint:recommended", 4 | "parserOptions": { 5 | "ecmaVersion": 6, 6 | "sourceType": "module", 7 | "ecmaFeatures": { 8 | "experimentalObjectRestSpread": true 9 | } 10 | }, 11 | "env": { 12 | "es6": true 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /src/SuperApi.js: -------------------------------------------------------------------------------- 1 | import EndPoint from "./EndPoint"; 2 | 3 | 4 | class SuperApi { 5 | constructor(endPointsConfig, defaultRequestConfig = {}) { 6 | this.reducers = {}; 7 | 8 | Object.keys(endPointsConfig).forEach((key) => { 9 | let endPoint = new EndPoint(key, {defaultRequestConfig, ...endPointsConfig[key]}); 10 | this[key] = endPoint; 11 | this.reducers[key] = endPoint.reduce.bind(endPoint); 12 | }); 13 | } 14 | } 15 | 16 | SuperApi.Endpoint = EndPoint; 17 | 18 | export default SuperApi; 19 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "redux-superapi", 3 | "version": "1.0.9", 4 | "description": "Create redux actions and reducers for REST endpoints", 5 | "main": "./lib/SuperApi.js", 6 | "scripts": { 7 | "prepublish": "npm run build", 8 | "build": "babel ./src -d ./lib", 9 | "test": "mocha --compilers js:babel-register ./test/*.js", 10 | "coverage": "istanbul cover _mocha -- -R spec --compilers js:babel-register ./test/*.js", 11 | "coveralls": "npm run coverage && ./node_modules/coveralls/bin/coveralls.js < coverage/lcov.info", 12 | "test:watch": "npm run test -- --watch", 13 | "lint": "eslint src/*.js test/*.js" 14 | }, 15 | "repository": { 16 | "type": "git", 17 | "url": "git+https://github.com/kayak/redux-superapi.git" 18 | }, 19 | "keywords": [ 20 | "redux", 21 | "ajax", 22 | "async", 23 | "rest", 24 | "api" 25 | ], 26 | "author": "Remi Koenig", 27 | "license": "Apache-2.0", 28 | "bugs": { 29 | "url": "https://github.com/kayak/redux-superapi/issues" 30 | }, 31 | "homepage": "https://github.com/kayak/redux-superapi#readme", 32 | "dependencies": { 33 | "axios": "^0.15.2" 34 | }, 35 | "devDependencies": { 36 | "axios-mock-adapter": "^1.7.1", 37 | "babel-cli": "^6.14.0", 38 | "babel-eslint": "^7.0.0", 39 | "babel-plugin-transform-object-rest-spread": "^6.8.0", 40 | "babel-preset-es2015": "^6.13.2", 41 | "chai": "^3.5.0", 42 | "chai-subset": "^1.3.0", 43 | "coveralls": "2.11.14", 44 | "eslint": "^3.3.1", 45 | "eslint-config-standard": "^6.0.0", 46 | "eslint-plugin-mocha": "^4.3.0", 47 | "eslint-plugin-promise": "^3.3.0", 48 | "eslint-plugin-standard": "^2.0.0", 49 | "istanbul": "1.1.0-alpha.1", 50 | "mocha": "^3.0.2", 51 | "mocha-lcov-reporter": "1.2.0", 52 | "redux": "^3.6.0", 53 | "redux-mock-store": "^1.2.0", 54 | "redux-thunk": "^2.1.0", 55 | "sinon": "^1.17.5", 56 | "sinon-chai": "^2.8.0" 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # redux-superapi 2 | 3 | [![Build Status](https://travis-ci.org/kayak/redux-superapi.png?branch=master)](https://travis-ci.org/kayak/redux-superapi) 4 | [![Coverage Status](https://coveralls.io/repos/github/kayak/redux-superapi/badge.svg?branch=master)](https://coveralls.io/github/kayak/redux-superapi?branch=master) 5 | [![Codacy Badge](https://api.codacy.com/project/badge/Grade/5cd791c56f4240728fdb6987c8397072)](https://www.codacy.com/app/remiremi/redux-superapi?utm_source=github.com&utm_medium=referral&utm_content=kayak/redux-superapi&utm_campaign=Badge_Grade) 6 | [![David](https://img.shields.io/david/kayak/redux-superapi.svg)](https://david-dm.org/kayak/redux-superapi) 7 | [![David](https://img.shields.io/david/dev/kayak/redux-superapi.svg)](https://david-dm.org/kayak/redux-superapi) 8 | 9 | `redux-superapi` generates actions and reducers for communicating with a REST backend. Its API is inspired from 10 | [redux-api](https://github.com/lexich/redux-api), and it uses [axios](https://github.com/mzabriskie/axios) for making 11 | the actual AJAX calls. Its goal is short, extensible and highly-readable code. 12 | 13 | ## Installation 14 | 15 | `npm install --save redux-superapi` 16 | 17 | ## Documentation 18 | 19 | ### Setup 20 | 21 | ``` 22 | var superApi = new SuperApi(endPointsConfig, defaultRequestConfig = {}) 23 | ``` 24 | 25 | Create a new SuperApi configuration. 26 | 27 | * `endPointsConfig` (required): map unique endpoint names to an object with: 28 | * `url` (required): url of the endpoint 29 | * `requestKey` (optional): function that returns a unique identifier of the request. See 30 | [making multiple requests for an endpoint](#making-multiple-requests-for-an-endpoint) 31 | * `defaultRequestConfig` (optional): default configuration passed on to axios, extending the configuration passed to the `SuperApi` 32 | constructor. 33 | * `defaultRequestConfig` (optional): pass a default request configuration that will be passed on to 34 | [axios](https://github.com/mzabriskie/axios) on every request. 35 | 36 | Sample endpoint configuration: 37 | 38 | ``` 39 | const endpoints = { 40 | experiments: { 41 | url: "/api/experiments/" 42 | }, 43 | experimentDetails: { 44 | url: "/api/experiments/:experimentId/", 45 | }, 46 | }; 47 | ``` 48 | 49 | Next, create a store with the SuperApi reducers. 50 | 51 | ``` 52 | createStore(combineReducers(superApi.reducers)); 53 | ``` 54 | 55 | ### Usage 56 | 57 | Dispatch any of the following actions: 58 | 59 | ``` 60 | superApi.endpointName.get(args, requestConfig = {}); 61 | superApi.endpointName.getOnce(args, requestConfig = {}); 62 | superApi.endpointName.delete(args, requestConfig = {}); 63 | superApi.endpointName.head(args, requestConfig = {}); 64 | superApi.endpointName.options(args, requestConfig = {}); 65 | superApi.endpointName.post(args, data, requestConfig = {}); 66 | superApi.endpointName.put(args, data, requestConfig = {}); 67 | superApi.endpointName.patch(args, data, requestConfig = {}); 68 | superApi.endpointName.reset(); 69 | ``` 70 | 71 | * `args` (required): dictionary mapping of arguments that need to be replaced in the URL. 72 | * `data` (required, only for post, put, patch): data to be passed to the server 73 | * `requestConfig`: configuration object passed on to axios. Extends the configuration set at the API/Endpoint levels. 74 | 75 | Example: `dispatch(superApi.experimentDetails.get({experimentId: 42}))` 76 | 77 | The `getOnce` method will not trigger a new request if there is already a pending request or if data has already been 78 | downloaded once. 79 | 80 | ### State 81 | 82 | The default state is: 83 | 84 | ``` 85 | { 86 | [endpointName]: { 87 | sync: false, 88 | syncing: false, 89 | loaded: false, 90 | data: {}, 91 | error: null 92 | } 93 | } 94 | ``` 95 | 96 | ### Chaining 97 | 98 | `dispatch` will always return a promise which you can chain with `.then()` or `.catch()`. 99 | 100 | ### Handling error 101 | 102 | State's `error` property will be axios' error message for malformed requests, or the data returned 103 | by the end point if the request went through but returned a response with an error status code. 104 | 105 | Since `dispatch` returns a promise you can handle the error with `dispatch(endPoint.get()).catch(...)`. 106 | 107 | ### Cancelling requests 108 | 109 | Dispatching `superApi.endpointName.reset()` will not only reset the state, it will also cancel any request that was 110 | started. Starting a new request will cancel any pending request automatically. 111 | 112 | ### Making multiple requests for an endpoint 113 | 114 | By default, you can only do one request at a time per endpoint. Doing another request will override the state and cancel 115 | the pending request. In some situations you actually want to be able to do multiple requests and store their state 116 | separately. 117 | 118 | This is possible by defining the `requestKey` endpoint option. `requestKey` should be a deterministic function that 119 | takes as sole argument a dictionary of the `args` for the request and returns a string (or anything that can be cast to 120 | string). 121 | 122 | ``` 123 | const endpoints = { 124 | experimentDetails: { 125 | url: "/api/experiments/:experimentId/", 126 | requestKey: (args) => args.experimentId 127 | }, 128 | }; 129 | ``` 130 | 131 | The state will then look like 132 | 133 | ``` 134 | { 135 | [endpointName]: { 136 | [experimentId]: { 137 | sync: false, 138 | syncing: false, 139 | loaded: false, 140 | data: {}, 141 | error: null 142 | } 143 | } 144 | } 145 | ``` 146 | 147 | There will be one separate entry for each different experimentId you call the API with, and they will all track their 148 | loading status and errors independently. 149 | 150 | For cancelling a request simply pass the `args` to `reset`: 151 | 152 | ``` 153 | superApi.endpointName.reset({experimentId: 42}) 154 | ``` 155 | 156 | ### Transformers and other advanced options 157 | 158 | A commonly used functionality is to transform the data received before saving it in the state. The best way to do this 159 | is to pass a `transformResponse` parameter to `axios`. 160 | 161 | ``` 162 | const endpoints = { 163 | experiments: { 164 | url: "/api/experiments/", 165 | defaultRequestConfig: { 166 | transformRequest: [function (data) { 167 | // Do whatever you want to transform the data 168 | 169 | return data; 170 | }], 171 | } 172 | }, 173 | }; 174 | ``` 175 | 176 | Similarly, `redux-superapi` doesn't implement any functionality that you can already configure with `axios` so it is a 177 | good idea to check out [axios documentation](https://github.com/mzabriskie/axios#request-config). 178 | 179 | ## Development 180 | 181 | Pull requests and issue reports are welcome. 182 | 183 | Build: 184 | 185 | `npm run build` 186 | 187 | Test: 188 | 189 | `npm run test` 190 | 191 | Lint: 192 | 193 | `npm run lint` 194 | 195 | ## License 196 | 197 | Copyright 2016 KAYAK Germany, GmbH 198 | 199 | Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at 200 | 201 | http://www.apache.org/licenses/LICENSE-2.0 202 | 203 | Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. 204 | -------------------------------------------------------------------------------- /src/EndPoint.js: -------------------------------------------------------------------------------- 1 | import axios from "axios"; 2 | 3 | let CancelToken = axios.CancelToken; 4 | 5 | class EndPoint { 6 | constructor(name, {url, requestKey, defaultRequestConfig}) { 7 | this.name = name; 8 | this.url = url; 9 | this.defaultRequestConfig = defaultRequestConfig || {}; 10 | this.isMultiRequest = !!requestKey; 11 | this.requestKey = requestKey || (() => 'default'); 12 | this.cancellation = {}; 13 | 14 | // Construct the methods for http methods that don't need data 15 | ['delete', 'get', 'head', 'options'].forEach((method) => { 16 | this[method] = (args, config = {}) => (dispatch) => this.request(dispatch, method, args, config); 17 | }); 18 | 19 | // Construct the methods for http methods that do need data 20 | ['post', 'put', 'patch'].forEach((method) => { 21 | this[method] = (args, data, config = {}) => (dispatch) => this.request(dispatch, method, args, config, data); 22 | }); 23 | } 24 | 25 | cancel(args) { 26 | let key = this.requestKey(args), 27 | cancellation = this.cancellation[key]; 28 | if (cancellation) { 29 | cancellation.cancel(); 30 | delete this.cancellation[key]; 31 | } 32 | } 33 | 34 | createCancellation(args) { 35 | let cancellation = CancelToken.source(); 36 | this.cancellation[this.requestKey(args)] = cancellation; 37 | return cancellation; 38 | } 39 | 40 | transformUrl(args = {}) { 41 | let url = this.url; 42 | // Replace all :arg with the actual value 43 | Object.keys(args).forEach((key) => { 44 | let argRe = new RegExp(':' + key + '(?=[^\w]|$)'); 45 | url = url.replace(argRe, args[key]); 46 | }); 47 | // Remove remaining arguments not present in args 48 | url = url.replace(/:[\w]+(?=[^\w]|$)/, ''); 49 | // Remove double slashes 50 | url = url.replace(/\/+/g, '/'); 51 | return url; 52 | } 53 | 54 | actionPrefix() { 55 | return '@@super-api@' + this.name + '_'; 56 | } 57 | 58 | isValidActionType(actionType) { 59 | return actionType && actionType.startsWith(this.actionPrefix()); 60 | } 61 | 62 | actionType(action) { 63 | return this.actionPrefix() + action; 64 | } 65 | 66 | actionSuccess(response, args) { 67 | return { 68 | type: this.actionType('success'), 69 | data: response.data, 70 | status: response.status, 71 | args 72 | }; 73 | } 74 | 75 | actionError(error, args) { 76 | if (error.response) { 77 | // Server responded with an error 78 | return { 79 | type: this.actionType('error'), 80 | error: error.response.data, 81 | status: error.response.status, 82 | args 83 | }; 84 | } else { 85 | // Request was malformed 86 | return { 87 | type: this.actionType('error'), 88 | error: error.message, 89 | args 90 | }; 91 | } 92 | } 93 | 94 | actionRequest(method, args) { 95 | return { 96 | type: this.actionType('request'), 97 | method, 98 | args 99 | }; 100 | } 101 | 102 | actionReset(args) { 103 | return { 104 | type: this.actionType('reset'), 105 | args 106 | }; 107 | } 108 | 109 | reset(args) { 110 | return dispatch => { 111 | this.cancel(args); 112 | dispatch(this.actionReset(args)) 113 | }; 114 | } 115 | 116 | getOnce(args, config = {}) { 117 | // Will fetch data only if it hasn't been fetched and hasn't started fetching. 118 | return (dispatch, getState) => { 119 | return this.requestOnce(dispatch, getState, 'get', args, config) 120 | } 121 | } 122 | 123 | requestOnce(dispatch, getState, method, args, config, data = undefined) { 124 | // Start the request only if there is no data already loaded or loading 125 | 126 | let key = this.requestKey(args); 127 | let state = getState(); 128 | 129 | if (state) { 130 | let _state = this.isMultiRequest ? state[key] : state; 131 | if (_state && (_state.sync || _state.syncing)) { 132 | return Promise.resolve(); 133 | } 134 | } 135 | 136 | return this.request(dispatch, method, args, config, data); 137 | } 138 | 139 | request(dispatch, method, args, config, data = undefined) { 140 | // Cancel any pending request 141 | this.cancel(args); 142 | 143 | dispatch(this.actionRequest(method, args)); 144 | 145 | return axios.request({ 146 | url: this.transformUrl(args), 147 | method: method, 148 | data: data, 149 | cancelToken: this.createCancellation(args).token, 150 | ...this.defaultRequestConfig[method], 151 | ...config 152 | }) 153 | .catch(error => { 154 | // First handle "operational errors", where the request did not complete as expected. 155 | dispatch(this.actionError(error, args)); 156 | throw error; // rethrow error for chaining 157 | }) 158 | .then(response => { 159 | // The .then handler happens after handling errors from the server ("operational errors") so that we 160 | // don't accidentally catch "programmers error". 161 | // See http://www.2ality.com/2016/03/promise-rejections-vs-exceptions.html 162 | dispatch(this.actionSuccess(response, args)); 163 | }); 164 | } 165 | 166 | reduce(state, action) { 167 | if (this.isMultiRequest) { 168 | return this.reduceMultiRequest(state, action) 169 | } else { 170 | return this.reduceRequest(state, action); 171 | } 172 | } 173 | 174 | reduceMultiRequest(state, action) { 175 | if (typeof state === 'undefined') { 176 | state = {}; 177 | } 178 | 179 | if (!this.isValidActionType(action.type)) { 180 | // Don't try to reduce an action coming from a different endpoint. 181 | return state; 182 | } else { 183 | let key = this.requestKey(action.args); 184 | 185 | return { 186 | ...state, 187 | [key]: this.reduceRequest(state[key], action) 188 | }; 189 | } 190 | } 191 | 192 | reduceRequest(state, action) { 193 | const defaultState = { 194 | loading: false, 195 | sync: false, 196 | syncing: false, 197 | data: {}, 198 | error: null 199 | }; 200 | 201 | if (typeof state === 'undefined') { 202 | state = defaultState; 203 | } 204 | 205 | switch (action.type) { 206 | case this.actionType('request'): 207 | return { 208 | ...state, 209 | loading: true, 210 | sync: false, 211 | syncing: true, 212 | error: null 213 | }; 214 | case this.actionType('success'): 215 | return { 216 | ...state, 217 | loading: false, 218 | sync: true, 219 | syncing: false, 220 | data: action.data, 221 | error: null 222 | }; 223 | case this.actionType('error'): 224 | return { 225 | ...state, 226 | loading: false, 227 | sync: false, 228 | syncing: false, 229 | error: action.error 230 | }; 231 | case this.actionType('reset'): 232 | return defaultState; 233 | default: 234 | return state; 235 | } 236 | } 237 | } 238 | 239 | 240 | EndPoint.axios = axios; // used for mocking in unit-tests 241 | 242 | 243 | export default EndPoint; -------------------------------------------------------------------------------- /LICENSE.txt: -------------------------------------------------------------------------------- 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 | -------------------------------------------------------------------------------- /test/EndPoint.js: -------------------------------------------------------------------------------- 1 | import chai, {expect} from "chai"; 2 | import chaiSubset from "chai-subset"; 3 | import EndPoint from "../src/EndPoint"; 4 | import sinon from "sinon"; 5 | import sinonChai from "sinon-chai"; 6 | import MockAdapter from "axios-mock-adapter"; 7 | import configureMockStore from "redux-mock-store"; 8 | import thunk from "redux-thunk"; 9 | 10 | const middlewares = [thunk]; 11 | const mockStore = configureMockStore(middlewares); 12 | 13 | var mock = new MockAdapter(EndPoint.axios, {delayResponse: 50}); 14 | mock.onAny('/api/error/').reply(500); 15 | mock.onAny(/.*/).reply(200); 16 | 17 | chai.use(chaiSubset); 18 | chai.use(sinonChai); 19 | 20 | function mockStoreWithReducer(reducer) { 21 | const store = mockStore(() => { 22 | return store.getActions().reduce(reducer, undefined); 23 | }); 24 | return store; 25 | } 26 | 27 | describe('EndPoint', () => { 28 | 29 | it('has all http methods', () => { 30 | const endPoint = new EndPoint('test', {url: '/api/buckets/'}); 31 | expect(endPoint).to.contain.all.keys(['delete', 'get', 'head', 'options', 'post', 'put', 'patch']); 32 | }); 33 | 34 | describe('.getOnce()', () => { 35 | it('only requests once with simultaneous requests', (done) => { 36 | const endPoint = new EndPoint('test', {url: '/api/buckets/'}); 37 | const store = mockStoreWithReducer(endPoint.reduce.bind(endPoint)); 38 | Promise.all([ 39 | store.dispatch(endPoint.getOnce()), 40 | store.dispatch(endPoint.getOnce()) 41 | ]).then(function() { 42 | expect(store.getActions().map(action => action.type)).to.eql([ 43 | '@@super-api@test_request', 44 | '@@super-api@test_success' 45 | ]); 46 | done(); 47 | }).catch(done); 48 | }); 49 | 50 | it('only requests once with non-simultaneous requests', (done) => { 51 | const endPoint = new EndPoint('test', {url: '/api/buckets/'}); 52 | const store = mockStoreWithReducer(endPoint.reduce.bind(endPoint)); 53 | store.dispatch(endPoint.getOnce()).then(function() { 54 | store.dispatch(endPoint.getOnce()).then(function() { 55 | expect(store.getActions().map(action => action.type)).to.eql([ 56 | '@@super-api@test_request', 57 | '@@super-api@test_success' 58 | ]); 59 | done(); 60 | }).catch(done); 61 | }).catch(done); 62 | }); 63 | }); 64 | 65 | describe('dispatch()', () => { 66 | it('creates _request and _success actions for a successful endPoint.get()', (done) => { 67 | const store = mockStore({}); 68 | const endPoint = new EndPoint('test', {url: '/api/buckets/'}); 69 | store.dispatch(endPoint.get()).then(function() { 70 | expect(store.getActions().map(action => action.type)).to.eql([ 71 | '@@super-api@test_request', 72 | '@@super-api@test_success' 73 | ]); 74 | done(); 75 | }).catch(done); 76 | }); 77 | 78 | it('creates _request and _error actions for a failed endPoint.get()', (done) => { 79 | const store = mockStore({}); 80 | const endPoint = new EndPoint('test', {url: '/api/error/'}); 81 | store.dispatch(endPoint.get()).catch(() => { 82 | expect(store.getActions().map(action => action.type)).to.eql([ 83 | '@@super-api@test_request', 84 | '@@super-api@test_error' 85 | ]); 86 | done(); 87 | }); 88 | }); 89 | 90 | it('aborts request on reset', () => { 91 | const store = mockStore({}); 92 | const endPoint = new EndPoint('test', {url: '/api/buckets/'}); 93 | sinon.spy(endPoint, 'cancel'); 94 | store.dispatch(endPoint.reset()); 95 | expect(endPoint.cancel).to.have.been.calledOnce; 96 | }); 97 | 98 | it('aborts request before starting a new one', () => { 99 | const store = mockStore({}); 100 | const endPoint = new EndPoint('test', {url: '/api/buckets/'}); 101 | sinon.spy(endPoint, 'cancel'); 102 | store.dispatch(endPoint.get()); 103 | expect(endPoint.cancel).to.have.been.calledOnce; 104 | }); 105 | 106 | it('does not swallow application exceptions in promise', (done) => { 107 | const store = mockStore({}); 108 | const endPoint = new EndPoint('test', {url: '/api/buckets/'}); 109 | store.subscribe(function() { 110 | const action = store.getActions().slice(-1)[0]; 111 | if (action.type === endPoint.actionType('success')) { 112 | throw new Error('Mock application error'); 113 | } 114 | }); 115 | store.dispatch(endPoint.get()).catch(function() { 116 | try { 117 | // Make sure the failure in dispatching 'success' did not trigger an 'error' action to be 118 | // dispatched, i.e. make sure the program failed. 119 | expect(store.getActions()).to.have.length(2); 120 | done(); 121 | } catch(err) { 122 | done(err); 123 | } 124 | }); 125 | }); 126 | }); 127 | 128 | describe('.transformUrl()', () => { 129 | it('can do nothing', function () { 130 | const endPoint = new EndPoint('test', {url: '/api/buckets/'}); 131 | expect(endPoint.transformUrl()).to.equal('/api/buckets/') 132 | }); 133 | 134 | it('can replace an argument', function () { 135 | const endPoint = new EndPoint('test', {url: '/api/buckets/:bucketId/'}); 136 | expect(endPoint.transformUrl({bucketId: 42})).to.equal('/api/buckets/42/') 137 | }); 138 | 139 | it('can replace final argument', function () { 140 | const endPoint = new EndPoint('test', {url: '/api/buckets/:bucketId'}); 141 | expect(endPoint.transformUrl({bucketId: 42})).to.equal('/api/buckets/42') 142 | }); 143 | 144 | it('removes unspecified arguments', function () { 145 | const endPoint = new EndPoint('test', {url: '/api/buckets/:bucketId/'}); 146 | expect(endPoint.transformUrl()).to.equal('/api/buckets/') 147 | }); 148 | }); 149 | 150 | 151 | describe('.reduce()', () => { 152 | const endPoint = new EndPoint('test', {url: '/api/buckets/'}); 153 | 154 | it('has correct default state', function () { 155 | expect(endPoint.reduce(undefined, {})).to.deep.equal({ 156 | loading: false, 157 | syncing: false, 158 | sync: false, 159 | data: {}, 160 | error: null 161 | }); 162 | }); 163 | 164 | it('transitions flags on request', function () { 165 | const oldState = { 166 | loading: false, 167 | syncing: false, 168 | sync: false 169 | }; 170 | const action = endPoint.actionRequest('get'); 171 | 172 | expect(endPoint.reduce(oldState, action)).to.containSubset({ 173 | loading: true, 174 | syncing: true, 175 | sync: false 176 | }); 177 | }); 178 | 179 | it('transitions flags on success', function () { 180 | const oldState = { 181 | loading: true, 182 | syncing: true, 183 | sync: false 184 | }; 185 | const action = endPoint.actionSuccess({}); 186 | 187 | expect(endPoint.reduce(oldState, action)).to.containSubset({ 188 | loading: false, 189 | syncing: false, 190 | sync: true, 191 | }); 192 | }); 193 | 194 | it('sets data on success', function () { 195 | const data = {sample: true}; 196 | const oldState = {data: {}}; 197 | const action = endPoint.actionSuccess(({data})); 198 | 199 | expect(endPoint.reduce(oldState, action).data).to.deep.equal(data); 200 | }); 201 | 202 | it('does not wipe data on new request', () => { 203 | const data = {sample: 42}; 204 | const oldState = {data}; 205 | const action = endPoint.actionRequest('get'); 206 | 207 | expect(endPoint.reduce(oldState, action).data).to.deep.equal(data); 208 | }); 209 | 210 | it('does not wipe data on error', () => { 211 | const data = {sample: 42}; 212 | const oldState = {data}; 213 | const action = endPoint.actionError('Some error'); 214 | 215 | expect(endPoint.reduce(oldState, action).data).to.deep.equal(data); 216 | }); 217 | }); 218 | 219 | }); 220 | 221 | 222 | describe('Multi-request Endpoint', () => { 223 | describe('.getOnce()', () => { 224 | it('only requests once with simultaneous requests', (done) => { 225 | const endPoint1 = new EndPoint('planet', { 226 | url: '/api/planets/:planetId/', 227 | requestKey: (args) => args.planetId 228 | }); 229 | const store = mockStoreWithReducer(endPoint1.reduce.bind(endPoint1)); 230 | Promise.all([ 231 | store.dispatch(endPoint1.getOnce({planetId: 42})), 232 | store.dispatch(endPoint1.getOnce({planetId: 42})) 233 | ]).then(function() { 234 | expect(store.getActions().map(action => action.type)).to.eql([ 235 | '@@super-api@planet_request', 236 | '@@super-api@planet_success' 237 | ]); 238 | done(); 239 | }).catch(done); 240 | }); 241 | 242 | it('only requests once with non-simultaneous requests', (done) => { 243 | const endPoint1 = new EndPoint('planet', { 244 | url: '/api/planets/:planetId/', 245 | requestKey: (args) => args.planetId 246 | }); 247 | const store = mockStoreWithReducer(endPoint1.reduce.bind(endPoint1)); 248 | store.dispatch(endPoint1.getOnce({planetId: 42})).then(function() { 249 | store.dispatch(endPoint1.getOnce({planetId: 42})).then(function() { 250 | expect(store.getActions().map(action => action.type)).to.eql([ 251 | '@@super-api@planet_request', 252 | '@@super-api@planet_success' 253 | ]); 254 | done(); 255 | }).catch(done); 256 | }).catch(done); 257 | }); 258 | }); 259 | 260 | describe('.reduce()', () => { 261 | const endPoint1 = new EndPoint('planet', { 262 | url: '/api/planets/:planetId/', 263 | requestKey: (args) => args.planetId 264 | }); 265 | 266 | const endPoint2 = new EndPoint('moon', { 267 | url: '/api/moons/:planetId/:moonId/', 268 | requestKey: (args) => [args.planetId, args.moonId].toString() 269 | }); 270 | 271 | it('has empty state by default', function () { 272 | expect(endPoint1.reduce(undefined, {})).to.be.empty; 273 | }); 274 | 275 | it("checks action type before setting initial state", function() { 276 | const action = endPoint1.actionReset(({planetId: 42})); 277 | expect(endPoint2.reduce(undefined, action)).to.be.empty; 278 | }); 279 | 280 | it('sets default state on reset', function () { 281 | const action = endPoint1.actionReset(({planetId: 42})); 282 | 283 | expect(endPoint1.reduce(undefined, action)).to.deep.equal({ 284 | '42': { 285 | loading: false, 286 | syncing: false, 287 | sync: false, 288 | data: {}, 289 | error: null 290 | } 291 | }); 292 | }); 293 | }); 294 | }); 295 | --------------------------------------------------------------------------------