├── .babelrc ├── .eslintignore ├── .eslintrc ├── .gitignore ├── .jestrc ├── .npmignore ├── .travis.yml ├── CHANGELOG.md ├── LICENSE ├── README.md ├── package-lock.json ├── package.json ├── src ├── createActionAsync.js ├── createReducerAsync.js └── index.js └── test ├── createActionAsync.test.js └── createReducerAsync.test.js /.babelrc: -------------------------------------------------------------------------------- 1 | { 2 | "presets": ["es2015", "stage-0"], 3 | "plugins": ["transform-object-rest-spread", "transform-runtime"] 4 | } 5 | -------------------------------------------------------------------------------- /.eslintignore: -------------------------------------------------------------------------------- 1 | lib/ 2 | -------------------------------------------------------------------------------- /.eslintrc: -------------------------------------------------------------------------------- 1 | { 2 | "parser": "babel-eslint", 3 | "plugins": [ 4 | 'mocha' 5 | ], 6 | "extends": ["eslint:recommended"], 7 | "env": { 8 | "browser": true, 9 | "es6": true, 10 | "node": true, 11 | "mocha": true 12 | }, 13 | "rules": { 14 | "no-debugger": 1, 15 | "no-console": 1 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | node_modules 2 | lib 3 | coverage 4 | -------------------------------------------------------------------------------- /.jestrc: -------------------------------------------------------------------------------- 1 | { 2 | "testEnvironment": "node", 3 | "collectCoverageFrom": [ 4 | "src/*.js" 5 | ], 6 | "coverageThreshold": { 7 | "global": { 8 | "branches": 100, 9 | "functions": 100, 10 | "lines": 100, 11 | "statements": 100 12 | } 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /.npmignore: -------------------------------------------------------------------------------- 1 | test 2 | coverage 3 | examples 4 | .babelrc 5 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: node_js 2 | node_js: 3 | - "5" 4 | after_success: 5 | - bash <(curl -s https://codecov.io/bash) 6 | 7 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/FredericHeem/redux-act-async/19b0acd894e6f77f631ace63fb4aefec0427c7d7/CHANGELOG.md -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | 2 | Apache License 3 | Version 2.0, January 2004 4 | http://www.apache.org/licenses/ 5 | 6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 7 | 8 | 1. Definitions. 9 | 10 | "License" shall mean the terms and conditions for use, reproduction, 11 | and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by 14 | the copyright owner that is granting the License. 15 | 16 | "Legal Entity" shall mean the union of the acting entity and all 17 | other entities that control, are controlled by, or are under common 18 | control with that entity. For the purposes of this definition, 19 | "control" means (i) the power, direct or indirect, to cause the 20 | direction or management of such entity, whether by contract or 21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 22 | outstanding shares, or (iii) beneficial ownership of such entity. 23 | 24 | "You" (or "Your") shall mean an individual or Legal Entity 25 | exercising permissions granted by this License. 26 | 27 | "Source" form shall mean the preferred form for making modifications, 28 | including but not limited to software source code, documentation 29 | source, and configuration files. 30 | 31 | "Object" form shall mean any form resulting from mechanical 32 | transformation or translation of a Source form, including but 33 | not limited to compiled object code, generated documentation, 34 | and conversions to other media types. 35 | 36 | "Work" shall mean the work of authorship, whether in Source or 37 | Object form, made available under the License, as indicated by a 38 | copyright notice that is included in or attached to the work 39 | (an example is provided in the Appendix below). 40 | 41 | "Derivative Works" shall mean any work, whether in Source or Object 42 | form, that is based on (or derived from) the Work and for which the 43 | editorial revisions, annotations, elaborations, or other modifications 44 | represent, as a whole, an original work of authorship. For the purposes 45 | of this License, Derivative Works shall not include works that remain 46 | separable from, or merely link (or bind by name) to the interfaces of, 47 | the Work and Derivative Works thereof. 48 | 49 | "Contribution" shall mean any work of authorship, including 50 | the original version of the Work and any modifications or additions 51 | to that Work or Derivative Works thereof, that is intentionally 52 | submitted to Licensor for inclusion in the Work by the copyright owner 53 | or by an individual or Legal Entity authorized to submit on behalf of 54 | the copyright owner. For the purposes of this definition, "submitted" 55 | means any form of electronic, verbal, or written communication sent 56 | to the Licensor or its representatives, including but not limited to 57 | communication on electronic mailing lists, source code control systems, 58 | and issue tracking systems that are managed by, or on behalf of, the 59 | Licensor for the purpose of discussing and improving the Work, but 60 | excluding communication that is conspicuously marked or otherwise 61 | designated in writing by the copyright owner as "Not a Contribution." 62 | 63 | "Contributor" shall mean Licensor and any individual or Legal Entity 64 | on behalf of whom a Contribution has been received by Licensor and 65 | subsequently incorporated within the Work. 66 | 67 | 2. Grant of Copyright License. Subject to the terms and conditions of 68 | this License, each Contributor hereby grants to You a perpetual, 69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 70 | copyright license to reproduce, prepare Derivative Works of, 71 | publicly display, publicly perform, sublicense, and distribute the 72 | Work and such Derivative Works in Source or Object form. 73 | 74 | 3. Grant of Patent License. Subject to the terms and conditions of 75 | this License, each Contributor hereby grants to You a perpetual, 76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 77 | (except as stated in this section) patent license to make, have made, 78 | use, offer to sell, sell, import, and otherwise transfer the Work, 79 | where such license applies only to those patent claims licensable 80 | by such Contributor that are necessarily infringed by their 81 | Contribution(s) alone or by combination of their Contribution(s) 82 | with the Work to which such Contribution(s) was submitted. If You 83 | institute patent litigation against any entity (including a 84 | cross-claim or counterclaim in a lawsuit) alleging that the Work 85 | or a Contribution incorporated within the Work constitutes direct 86 | or contributory patent infringement, then any patent licenses 87 | granted to You under this License for that Work shall terminate 88 | as of the date such litigation is filed. 89 | 90 | 4. Redistribution. You may reproduce and distribute copies of the 91 | Work or Derivative Works thereof in any medium, with or without 92 | modifications, and in Source or Object form, provided that You 93 | meet the following conditions: 94 | 95 | (a) You must give any other recipients of the Work or 96 | Derivative Works a copy of this License; and 97 | 98 | (b) You must cause any modified files to carry prominent notices 99 | stating that You changed the files; and 100 | 101 | (c) You must retain, in the Source form of any Derivative Works 102 | that You distribute, all copyright, patent, trademark, and 103 | attribution notices from the Source form of the Work, 104 | excluding those notices that do not pertain to any part of 105 | the Derivative Works; and 106 | 107 | (d) If the Work includes a "NOTICE" text file as part of its 108 | distribution, then any Derivative Works that You distribute must 109 | include a readable copy of the attribution notices contained 110 | within such NOTICE file, excluding those notices that do not 111 | pertain to any part of the Derivative Works, in at least one 112 | of the following places: within a NOTICE text file distributed 113 | as part of the Derivative Works; within the Source form or 114 | documentation, if provided along with the Derivative Works; or, 115 | within a display generated by the Derivative Works, if and 116 | wherever such third-party notices normally appear. The contents 117 | of the NOTICE file are for informational purposes only and 118 | do not modify the License. You may add Your own attribution 119 | notices within Derivative Works that You distribute, alongside 120 | or as an addendum to the NOTICE text from the Work, provided 121 | that such additional attribution notices cannot be construed 122 | as modifying the License. 123 | 124 | You may add Your own copyright statement to Your modifications and 125 | may provide additional or different license terms and conditions 126 | for use, reproduction, or distribution of Your modifications, or 127 | for any such Derivative Works as a whole, provided Your use, 128 | reproduction, and distribution of the Work otherwise complies with 129 | the conditions stated in this License. 130 | 131 | 5. Submission of Contributions. Unless You explicitly state otherwise, 132 | any Contribution intentionally submitted for inclusion in the Work 133 | by You to the Licensor shall be under the terms and conditions of 134 | this License, without any additional terms or conditions. 135 | Notwithstanding the above, nothing herein shall supersede or modify 136 | the terms of any separate license agreement you may have executed 137 | with Licensor regarding such Contributions. 138 | 139 | 6. Trademarks. This License does not grant permission to use the trade 140 | names, trademarks, service marks, or product names of the Licensor, 141 | except as required for reasonable and customary use in describing the 142 | origin of the Work and reproducing the content of the NOTICE file. 143 | 144 | 7. Disclaimer of Warranty. Unless required by applicable law or 145 | agreed to in writing, Licensor provides the Work (and each 146 | Contributor provides its Contributions) on an "AS IS" BASIS, 147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 148 | implied, including, without limitation, any warranties or conditions 149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 150 | PARTICULAR PURPOSE. You are solely responsible for determining the 151 | appropriateness of using or redistributing the Work and assume any 152 | risks associated with Your exercise of permissions under this License. 153 | 154 | 8. Limitation of Liability. In no event and under no legal theory, 155 | whether in tort (including negligence), contract, or otherwise, 156 | unless required by applicable law (such as deliberate and grossly 157 | negligent acts) or agreed to in writing, shall any Contributor be 158 | liable to You for damages, including any direct, indirect, special, 159 | incidental, or consequential damages of any character arising as a 160 | result of this License or out of the use or inability to use the 161 | Work (including but not limited to damages for loss of goodwill, 162 | work stoppage, computer failure or malfunction, or any and all 163 | other commercial damages or losses), even if such Contributor 164 | has been advised of the possibility of such damages. 165 | 166 | 9. Accepting Warranty or Additional Liability. While redistributing 167 | the Work or Derivative Works thereof, You may choose to offer, 168 | and charge a fee for, acceptance of support, warranty, indemnity, 169 | or other liability obligations and/or rights consistent with this 170 | License. However, in accepting such obligations, You may act only 171 | on Your own behalf and on Your sole responsibility, not on behalf 172 | of any other Contributor, and only if You agree to indemnify, 173 | defend, and hold each Contributor harmless for any liability 174 | incurred by, or claims asserted against, such Contributor by reason 175 | of your accepting any such warranty or additional liability. 176 | 177 | END OF TERMS AND CONDITIONS 178 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # redux-act-async 2 | 3 | Create async actions and reducers based on [redux-act](https://github.com/pauldijou/redux-act) 4 | 5 | ## Install 6 | 7 | ```bash 8 | npm install redux-act-async --save 9 | ``` 10 | 11 | ## Badges 12 | 13 | [![Build Status](https://travis-ci.org/FredericHeem/redux-act-async.svg?branch=master)](https://travis-ci.org/FredericHeem/redux-act-async) 14 | 15 | [![codecov](https://codecov.io/gh/FredericHeem/redux-act-async/branch/master/graph/badge.svg)](https://codecov.io/gh/FredericHeem/redux-act-async) 16 | 17 | [![npm version](https://badge.fury.io/js/redux-act-async.svg)](https://badge.fury.io/js/redux-act-async) 18 | ## Usage 19 | 20 | ```js 21 | 22 | import thunk from 'redux-thunk' 23 | import {createStore, applyMiddleware} from 'redux'; 24 | import {createActionAsync, createReducerAsync} from 'redux-act-async'; 25 | 26 | // The async api to call, must be a function that returns a promise 27 | let user = {id: 8}; 28 | function apiOk(){ 29 | return Promise.resolve(user); 30 | } 31 | 32 | // createActionAsync will create 4 synchronous action creators: 33 | // login.request, login.ok, login.error and login.reset 34 | const login = createActionAsync('LOGIN', apiOk); 35 | 36 | /* 37 | createReducerAsync takes an async action created by createActionAsync. 38 | It reduces the following state given the four actions: request, ok, error and reset. 39 | const defaultsState = { 40 | loading: false, 41 | request: null, 42 | data: null, 43 | error: null 44 | }; 45 | 46 | if you need to overwrite the defaultsState just insert your initialState as a second paramenter in the createReducerAsync function. Just like that: 47 | 48 | const initialState = { 49 | loading: false, 50 | request: null, 51 | data: {custom: "intitial data"}, 52 | error: null 53 | }; 54 | 55 | const reducer = createReducerAsync(login, initialState) 56 | 57 | */ 58 | const reducer = createReducerAsync(login) 59 | 60 | const store = createStore(reducer, applyMiddleware(thunk)); 61 | 62 | await store.dispatch(login({username:'lolo', password: 'password'})); 63 | 64 | ``` 65 | 66 | ## Legacy redux 67 | 68 | In a nutshell, the following code: 69 | 70 | ```js 71 | const options = {noRethrow: false}; 72 | const loginAction = createActionAsync('LOGIN', api, options); 73 | const loginReducer = createReducerAsync(loginAction) 74 | ``` 75 | 76 | is equivalent to: 77 | 78 | ```js 79 | const LOGIN_REQUEST = 'LOGIN_REQUEST' 80 | const LOGIN_OK = 'LOGIN_OK' 81 | const LOGIN_ERROR = 'LOGIN_ERROR' 82 | const LOGIN_RESET = 'LOGIN_RESET' 83 | 84 | const loginRequest = (value) => ({ 85 | type: LOGIN_REQUEST, 86 | payload: value 87 | }) 88 | 89 | const loginOk = (value) => ({ 90 | type: LOGIN_OK, 91 | payload: value 92 | }) 93 | 94 | const loginError = (value) => ({ 95 | type: LOGIN_ERROR, 96 | payload: value 97 | }) 98 | 99 | const loginReset = (value) => ({ 100 | type: LOGIN_RESET, 101 | payload: value 102 | }) 103 | 104 | const options = {noRethrow: true}; 105 | 106 | export const login = (...args) => { 107 | return (dispatch, getState) => { 108 | dispatch(loginRequest(...args)); 109 | return api(...args, dispatch, getState) 110 | .then(response => { 111 | const out = { 112 | request: args, 113 | response: response 114 | } 115 | 116 | dispatch(loginOk(out)) 117 | return out; 118 | }) 119 | .catch(error => { 120 | const errorOut = { 121 | actionAsync, 122 | request: args, 123 | error: error 124 | } 125 | dispatch(loginError(errorOut)) 126 | if(!options.noRethrow) throw errorOut; 127 | }) 128 | } 129 | } 130 | 131 | const defaultsState = { 132 | loading: false, 133 | request: null, 134 | data: null, 135 | error: null 136 | }; 137 | 138 | const reducer = createReducer({ 139 | [actionAsync.request]: (state, payload) => ({ 140 | ...state, 141 | request: payload, 142 | loading: true, 143 | data: null, 144 | error: null 145 | }), 146 | [actionAsync.ok]: (state, payload) => ({ 147 | ...state, 148 | loading: false, 149 | data: payload.response 150 | }), 151 | [actionAsync.error]: (state, payload) => ({ 152 | ...state, 153 | loading: false, 154 | error: payload.error 155 | }), 156 | [actionAsync.reset]: () => (defaultsState) 157 | } , defaultsState); 158 | 159 | 160 | ``` 161 | 162 | That's 3 lines against 78 lines, a good way to reduce boilerplate code. 163 | 164 | ## Async Action Options 165 | 166 | Here are all the options to configure an asynchronous action: 167 | 168 | ```javascript 169 | const actionOptions = { 170 | noRethrow: false, 171 | request:{ 172 | callback: (dispatch, getState, ...args) => { 173 | }, 174 | payloadReducer: (payload) => { 175 | return payload 176 | }, 177 | metaReducer: (meta) => { 178 | return ASYNC_META.REQUEST 179 | } 180 | }, 181 | ok:{ 182 | callback: (dispatch, getState, ...args) => { 183 | }, 184 | payloadReducer: (payload) => { 185 | return payload 186 | }, 187 | metaReducer: () => { 188 | return ASYNC_META.OK 189 | } 190 | }, 191 | error:{ 192 | callback: (dispatch, getState, ...args) => { 193 | }, 194 | payloadReducer: (payload) => { 195 | return payload 196 | }, 197 | metaReducer: () => { 198 | return ASYNC_META.ERROR 199 | } 200 | } 201 | } 202 | 203 | const loginAction = createActionAsync('LOGIN', api, actionOptions); 204 | 205 | ``` 206 | ## Who is using this library ? 207 | 208 | This library has been extracted originally from [starhack.it](https://github.com/FredericHeem/starhackit), a React/Node Full Stack Starter Kit. 209 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "redux-act-async", 3 | "version": "1.7.0", 4 | "license": "Apache-2.0", 5 | "description": "Reducing the boilerplate of redux asynchronous applications", 6 | "keywords": [ 7 | "async", 8 | "redux", 9 | "flux", 10 | "action", 11 | "reducer" 12 | ], 13 | "main": "lib/index.js", 14 | "homepage": "https://github.com/FredericHeem/redux-act-async", 15 | "author": { 16 | "name": "Frederic Heem", 17 | "url": "https://github.com/FredericHeem" 18 | }, 19 | "repository": { 20 | "type": "git", 21 | "url": "https://github.com/FredericHeem/redux-act-async" 22 | }, 23 | "bugs": { 24 | "url": "https://github.com/FredericHeem/redux-act-async/issues" 25 | }, 26 | "devDependencies": { 27 | "babel-cli": "6.18.0", 28 | "babel-core": "6.18.2", 29 | "babel-eslint": "7.1.1", 30 | "babel-plugin-transform-object-rest-spread": "6.19.0", 31 | "babel-plugin-transform-runtime": "6.15.0", 32 | "babel-preset-es2015": "6.18.0", 33 | "babel-preset-stage-0": "6.16.0", 34 | "chai": "3.5.0", 35 | "chai-spies": "0.7.1", 36 | "eslint": "3.11.1", 37 | "eslint-config-standard": "6.2.1", 38 | "eslint-loader": "1.6.1", 39 | "eslint-plugin-babel": "4.0.0", 40 | "eslint-plugin-promise": "3.4.0", 41 | "eslint-plugin-standard": "2.0.1", 42 | "isparta": "4.0.0", 43 | "jest-cli": "17.0.3", 44 | "lodash": "4.17.2", 45 | "redux": "3.6.0", 46 | "redux-logger": "2.7.4", 47 | "redux-thunk": "2.1.0", 48 | "rimraf": "2.5.4" 49 | }, 50 | "scripts": { 51 | "clean": "rimraf lib", 52 | "build": "babel src --out-dir lib", 53 | "lint": "eslint .", 54 | "prepublish": "npm run clean && npm run build", 55 | "test": "jest --coverage", 56 | "watch:test": "jest --watch", 57 | "version": "npm test", 58 | "postversion": "git push && git push --tags" 59 | }, 60 | "dependencies": { 61 | "babel-runtime": "^6.18.0", 62 | "object-assign": "^4.1.1", 63 | "redux-act": "^1.1.0" 64 | } 65 | } 66 | -------------------------------------------------------------------------------- /src/createActionAsync.js: -------------------------------------------------------------------------------- 1 | import {createAction} from 'redux-act' 2 | import objectAssign from 'object-assign'; 3 | 4 | export const ASYNC_META = { 5 | REQUEST: "REQUEST", 6 | OK: "OK", 7 | ERROR: "ERROR", 8 | RESET: "RESET" 9 | } 10 | 11 | const defaultOption = { 12 | noRethrow: false, 13 | request:{ 14 | metaReducer: (meta) => { 15 | return ASYNC_META.REQUEST 16 | } 17 | }, 18 | ok:{ 19 | metaReducer: () => { 20 | return ASYNC_META.OK 21 | } 22 | }, 23 | error:{ 24 | metaReducer: () => { 25 | return ASYNC_META.ERROR 26 | } 27 | } 28 | } 29 | 30 | export default function createActionAsync(description, api, options = defaultOption) { 31 | 32 | options = { 33 | noRethrow: options.noRethrow !== undefined ? options.noRethrow : defaultOption.noRethrow, 34 | request: objectAssign({}, defaultOption.request, options.request), 35 | ok: objectAssign({}, defaultOption.ok, options.ok), 36 | error: objectAssign({}, defaultOption.error, options.error) 37 | }; 38 | 39 | let actions = { 40 | request: createAction(`${description}_${ASYNC_META.REQUEST}`, options.request.payloadReducer, options.request.metaReducer), 41 | ok: createAction(`${description}_${ASYNC_META.OK}`, options.ok.payloadReducer, options.ok.metaReducer), 42 | error: createAction(`${description}_${ASYNC_META.ERROR}`, options.error.payloadReducer, options.error.metaReducer), 43 | reset: createAction(`${description}_${ASYNC_META.RESET}`) 44 | } 45 | 46 | let actionAsync = (...args) => { 47 | return (dispatch, getState) => { 48 | dispatch(actions.request(...args)); 49 | if(options.request.callback) options.request.callback(dispatch, getState, ...args); 50 | return api(...args, dispatch, getState) 51 | .then(response => { 52 | const out = { 53 | request: args, 54 | response: response 55 | } 56 | 57 | dispatch(actions.ok(out)) 58 | if(options.ok.callback) options.ok.callback(dispatch, getState, response, ...args); 59 | return out; 60 | }) 61 | .catch(error => { 62 | const errorOut = { 63 | actionAsync, 64 | request: args, 65 | error: error 66 | } 67 | dispatch(actions.error(errorOut)) 68 | if(options.error.callback) options.error.callback(dispatch, getState, errorOut, ...args); 69 | if(!options.noRethrow) throw errorOut; 70 | }) 71 | } 72 | } 73 | 74 | objectAssign(actionAsync, actions); 75 | actionAsync.options = options; 76 | return actionAsync; 77 | } 78 | -------------------------------------------------------------------------------- /src/createReducerAsync.js: -------------------------------------------------------------------------------- 1 | import {createReducer} from 'redux-act'; 2 | 3 | const defaultsState = { 4 | loading: false, 5 | request: null, 6 | data: null, 7 | error: null 8 | }; 9 | 10 | export default function createReducerAsync(actionAsync, defaultState = defaultsState) { 11 | return createReducer({ 12 | [actionAsync.request]: (state, payload) => ({ 13 | ...state, 14 | request: payload, 15 | loading: true, 16 | error: null 17 | }), 18 | [actionAsync.ok]: (state, payload) => ({ 19 | ...state, 20 | loading: false, 21 | data: payload.response 22 | }), 23 | [actionAsync.error]: (state, payload) => ({ 24 | ...state, 25 | loading: false, 26 | error: payload.error 27 | }), 28 | [actionAsync.reset]: () => (defaultState) 29 | }, defaultState); 30 | } 31 | -------------------------------------------------------------------------------- /src/index.js: -------------------------------------------------------------------------------- 1 | import createActionAsync, {ASYNC_META} from './createActionAsync'; 2 | import createReducerAsync from './createReducerAsync'; 3 | 4 | export { 5 | ASYNC_META, 6 | createActionAsync, 7 | createReducerAsync 8 | } 9 | -------------------------------------------------------------------------------- /test/createActionAsync.test.js: -------------------------------------------------------------------------------- 1 | import _ from 'lodash'; 2 | import chai, {assert} from 'chai'; 3 | import spies from 'chai-spies'; 4 | import thunk from 'redux-thunk' 5 | import {createStore, applyMiddleware} from 'redux'; 6 | import {createReducer} from 'redux-act'; 7 | import {createActionAsync, ASYNC_META} from '../src/index'; 8 | import {createReducerAsync} from '../src/index'; 9 | 10 | const expect = chai.expect; 11 | chai.use(spies); 12 | 13 | describe('createActionAsync', function () { 14 | const param = {username:'lolo', password: 'password'}; 15 | 16 | it('should support all format', function () { 17 | let actionName = 'LOGIN_1'; 18 | const login = createActionAsync(actionName, () => Promise.resolve()); 19 | expect(login).to.be.a('function'); 20 | expect(login.request).to.be.a('function'); 21 | expect(login.ok).to.be.a('function'); 22 | expect(login.error).to.be.a('function'); 23 | expect(login.reset).to.be.a('function'); 24 | }); 25 | 26 | it('run the action, ok', async () => { 27 | let actionName = 'LOGIN_2'; 28 | 29 | function apiOk(/*param*/){ 30 | return Promise.resolve({user_id:1}); 31 | } 32 | const login = createActionAsync(actionName, apiOk); 33 | let run = login(param); 34 | let metas = []; 35 | function dispatch(action){ 36 | metas.push(action.meta); 37 | } 38 | await run(dispatch); 39 | assert.deepEqual(metas, [ASYNC_META.REQUEST, ASYNC_META.OK]); 40 | }); 41 | it('run the action, ko', async () => { 42 | let actionName = 'LOGIN_3'; 43 | let error = {name: 'myError'}; 44 | function apiError(){ 45 | return Promise.reject(error); 46 | } 47 | const login = createActionAsync(actionName, apiError); 48 | let run = login(param); 49 | let metas = []; 50 | function dispatch(action){ 51 | metas.push(action.meta); 52 | } 53 | try { 54 | await run(dispatch); 55 | } catch(error){ 56 | 57 | } 58 | assert.deepEqual(metas, [ASYNC_META.REQUEST, ASYNC_META.ERROR]); 59 | }); 60 | 61 | it('run the action, but do not rethrow error', function() { 62 | 63 | let actionName = 'LOGIN_4'; 64 | let error = {name: 'myError'}; 65 | function apiError(){ 66 | return Promise.reject(error); 67 | } 68 | const login = createActionAsync(actionName, apiError, {noRethrow: true}); 69 | let run = login({username:'lolo', password: 'password'}); 70 | function dispatch(/*action*/){ 71 | } 72 | 73 | return run(dispatch).catch(function(/*error*/){ 74 | assert(false, 'when throwing is turned off, should not hit this path'); 75 | }); 76 | }); 77 | 78 | it('run the action, throw error explicitely', function() { 79 | 80 | let actionName = 'LOGIN_5'; 81 | let error = {name: 'myError'}; 82 | function apiError(){ 83 | return Promise.reject(error); 84 | } 85 | const login = createActionAsync(actionName, apiError); 86 | let run = login(param); 87 | function dispatch(action){ 88 | assert(action) 89 | //console.log('dispatch action:', action); 90 | } 91 | 92 | return run(dispatch).catch(function(error) { 93 | //console.log('dispatch error:', error); 94 | assert(_.isFunction(error.actionAsync), "error.actionAsync should be a function"); 95 | expect(error.request[0]).to.be.equal(param); 96 | expect(error.error.name).to.be.equal('myError'); 97 | }); 98 | }); 99 | 100 | it('run the action with multiple parameters', async () => { 101 | let actionName = 'LOGIN_6'; 102 | let user = {id: 8}; 103 | function apiOk(username, password){ 104 | assert.equal(username, 'ciccio'); 105 | assert.equal(password, 'password'); 106 | return Promise.resolve(user); 107 | } 108 | const login = createActionAsync(actionName, apiOk); 109 | const reducer = createReducerAsync(login); 110 | const store = createStore(reducer, applyMiddleware(thunk)); 111 | 112 | let run = login('ciccio', 'password'); 113 | 114 | const {response} = await store.dispatch(run); 115 | assert.equal(response, user); 116 | }); 117 | 118 | it('run the action with dispatch and getState-function as parameter', async () => { 119 | let actionName = 'LOGIN_8'; 120 | let user = {id: 8}; 121 | function apiOk(username, password, dispatch, getState) { 122 | assert.equal(username, 'ciccio'); 123 | assert.equal(password, 'password'); 124 | expect(dispatch).to.be.a('function'); 125 | expect(getState).to.be.a('function'); 126 | return Promise.resolve(user); 127 | } 128 | const login = createActionAsync(actionName, apiOk); 129 | const reducer = createReducerAsync(login); 130 | const store = createStore(reducer, applyMiddleware(thunk)); 131 | let run = login('ciccio', 'password'); 132 | 133 | await store.dispatch(run); 134 | 135 | }); 136 | 137 | it('payloadReducer and metaReducer in options', function () { 138 | let actionName = 'LOGIN_7'; 139 | let loginUser = { 140 | username: 'ciccio', 141 | password: 'password' 142 | }; 143 | let user = {id: 8}; 144 | function apiOk(/*username, password*/){ 145 | return Promise.resolve(user); 146 | } 147 | 148 | const options = { 149 | request:{ 150 | payloadReducer: (username, password) => { 151 | //console.log('request payloadReducer ', username, password) 152 | assert.equal(username, loginUser.username); 153 | assert.equal(password, loginUser.password); 154 | return {username, password} 155 | }, 156 | metaReducer: (meta) => { 157 | //console.log('request metaReducer ', meta) 158 | return meta 159 | } 160 | }, 161 | ok:{ 162 | payloadReducer: (payload, username, password) => { 163 | //console.log('ok payloadReducer ', payload) 164 | assert.equal(username, loginUser.username); 165 | assert.equal(password, loginUser.password); 166 | return payload 167 | }, 168 | metaReducer: (meta) => { 169 | //console.log('ok metaReducer ', meta) 170 | return meta 171 | } 172 | }, 173 | error:{ 174 | payloadReducer: (payload, username, password) => { 175 | //console.log('error payloadReducer ', payload) 176 | assert.equal(username, loginUser.username); 177 | assert.equal(password, loginUser.password); 178 | return payload 179 | }, 180 | metaReducer: (meta) => { 181 | //console.log('error metaReducer ', meta) 182 | return meta 183 | } 184 | } 185 | } 186 | 187 | const login = createActionAsync(actionName, apiOk, options); 188 | const reducer = createReducerAsync(login); 189 | const store = createStore(reducer, applyMiddleware(thunk)); 190 | 191 | let run = login(loginUser.username, loginUser.password); 192 | 193 | store.dispatch(run); 194 | }); 195 | it('simple use case with reducer and store', async () => { 196 | let actionName = 'LOGIN_9'; 197 | let user = {id: 8}; 198 | function apiOk(){ 199 | return Promise.resolve(user); 200 | } 201 | const login = createActionAsync(actionName, apiOk); 202 | const initialState = { 203 | authenticated: false, 204 | }; 205 | 206 | let reducer = createReducer({ 207 | [login.request]: (state, payload) => { 208 | assert(payload); 209 | //console.log('login.request ', payload); 210 | }, 211 | [login.ok]: (state, payload) => { 212 | assert(payload); 213 | //console.log('login.ok ', payload.request); 214 | //console.log('login.ok ', payload.response); 215 | }, 216 | [login.error]: (state, payload) => { 217 | assert(payload); 218 | //console.log('login.error ', payload); 219 | } 220 | }, initialState); 221 | 222 | 223 | const store = createStore(reducer, applyMiddleware(thunk)); 224 | 225 | 226 | let run = login(param); 227 | 228 | await store.dispatch(run); 229 | 230 | }); 231 | it('multiple tabs', async () => { 232 | let actionName = 'TAB'; 233 | let user = {id: 8}; 234 | function apiOk(){ 235 | return Promise.resolve(user); 236 | } 237 | const tabActionAsync = createActionAsync(actionName, apiOk); 238 | 239 | const initialState = { 240 | data: new Map(), 241 | loading: new Map() 242 | }; 243 | 244 | function reducer(state = initialState, action) { 245 | switch (action.type) { 246 | case tabActionAsync.request.getType():{ 247 | //console.log('tab.request ', action); 248 | return { 249 | ...state, 250 | request: action.payload 251 | } 252 | } 253 | case tabActionAsync.ok.getType():{ 254 | //console.log('tab.ok ', action); 255 | return { 256 | ...state, 257 | data: action.payload.response 258 | } 259 | } 260 | default: 261 | return state 262 | } 263 | } 264 | 265 | const store = createStore(reducer, applyMiddleware(thunk)); 266 | await store.dispatch(tabActionAsync('tab1')); 267 | //console.log("state ", store.getState()); 268 | }); 269 | 270 | it('options', () => { 271 | let actionName = 'LOGIN_10'; 272 | function apiOk(payload){ 273 | return Promise.resolve(payload); 274 | } 275 | 276 | const option = { 277 | noRethrow: false, 278 | request: { 279 | payloadReducer: (payload) => { 280 | return payload 281 | } 282 | } 283 | } 284 | 285 | const login = createActionAsync(actionName, apiOk, option); 286 | assert(login.options); 287 | assert(login.options.request.payloadReducer); 288 | assert(login.options.request.metaReducer); 289 | 290 | }); 291 | it('callback in options', function () { 292 | let actionName = 'LOGIN_11'; 293 | let loginUser = { 294 | username: 'ciccio', 295 | password: 'password' 296 | }; 297 | let user = {id: 8}; 298 | function apiOk(username, password){ 299 | if(password === 'password'){ 300 | return Promise.resolve(user); 301 | } else { 302 | return Promise.reject({name:"InvalidPassword"}); 303 | } 304 | } 305 | 306 | const options = { 307 | request:{ 308 | callback: (dispatch, getState, ...args) => { 309 | assert(dispatch); 310 | assert(getState); 311 | } 312 | }, 313 | ok:{ 314 | callback: (dispatch, getState, ...args) => { 315 | assert(dispatch); 316 | assert(getState); 317 | } 318 | }, 319 | error:{ 320 | callback: (dispatch, getState, ...args) => { 321 | assert(dispatch); 322 | assert(getState); 323 | } 324 | } 325 | } 326 | 327 | const login = createActionAsync(actionName, apiOk, options); 328 | const reducer = createReducerAsync(login); 329 | const store = createStore(reducer, applyMiddleware(thunk)); 330 | 331 | store.dispatch(login(loginUser.username, loginUser.password)); 332 | store.dispatch(login(loginUser.username, "babpassword")); 333 | }); 334 | }); 335 | -------------------------------------------------------------------------------- /test/createReducerAsync.test.js: -------------------------------------------------------------------------------- 1 | import _ from 'lodash'; 2 | import chai, {assert} from 'chai'; 3 | import spies from 'chai-spies'; 4 | import thunk from 'redux-thunk' 5 | import {createStore, applyMiddleware} from 'redux'; 6 | import {createActionAsync} from '../src/index'; 7 | import {createReducerAsync} from '../src/index'; 8 | 9 | chai.use(spies); 10 | 11 | describe('createReducerAsync', function () { 12 | 13 | it('run the action, ok', async () => { 14 | const actionName = 'LOGIN_12'; 15 | const user = {id: 8}; 16 | function apiOk(){ 17 | //console.log('apiOk'); 18 | return Promise.resolve(user); 19 | } 20 | const login = createActionAsync(actionName, apiOk); 21 | 22 | let reducer = createReducerAsync(login) 23 | 24 | const store = createStore(reducer, applyMiddleware(thunk)); 25 | //console.log(store.getState()) 26 | const params = {username:'lolo', password: 'password'}; 27 | let run = login(params); 28 | 29 | await store.dispatch(run); 30 | //console.log(store.getState()) 31 | assert(_.isEqual(store.getState().request, params)) 32 | assert.isFalse(store.getState().loading) 33 | 34 | // Reset the state 35 | await store.dispatch(login.reset()); 36 | //console.log(store.getState()) 37 | const state = store.getState(); 38 | assert.isNull(state.data) 39 | assert.isNull(state.error) 40 | assert.isNull(state.request) 41 | assert.isFalse(state.loading) 42 | }); 43 | 44 | it('run the action, ko', async () => { 45 | const actionName = 'LOGIN_13'; 46 | const error = {name: 'myError'}; 47 | function apiError(){ 48 | return Promise.reject(error); 49 | } 50 | const login = createActionAsync(actionName, apiError, {noRethrow: true}); 51 | 52 | const initialState = { 53 | loading: false, 54 | authenticated: false, 55 | }; 56 | 57 | let reducer = createReducerAsync(login, initialState) 58 | 59 | const store = createStore(reducer, applyMiddleware(thunk)); 60 | 61 | const params = {username:'lolo', password: 'password'}; 62 | let run = login(params); 63 | 64 | await store.dispatch(run); 65 | //console.log("state: ", store.getState()); 66 | assert(_.isEqual(store.getState().request, params)) 67 | assert.equal(store.getState().error, error) 68 | assert.isFalse(store.getState().loading) 69 | }); 70 | }); 71 | --------------------------------------------------------------------------------