├── .babelrc ├── .eslintrc ├── .gitignore ├── LICENSE.md ├── README.md ├── package.json ├── src └── index.js ├── test └── index.js └── webpack.config.babel.js /.babelrc: -------------------------------------------------------------------------------- 1 | { 2 | "plugins": [ 3 | ["transform-es2015-template-literals", { "loose": true }], 4 | "transform-es2015-literals", 5 | "transform-es2015-function-name", 6 | "transform-es2015-arrow-functions", 7 | "transform-es2015-block-scoped-functions", 8 | ["transform-es2015-classes", { "loose": true }], 9 | "transform-es2015-object-super", 10 | "transform-es2015-shorthand-properties", 11 | ["transform-es2015-computed-properties", { "loose": true }], 12 | ["transform-es2015-for-of", { "loose": true }], 13 | "transform-es2015-sticky-regex", 14 | "transform-es2015-unicode-regex", 15 | "check-es2015-constants", 16 | ["transform-es2015-spread", { "loose": true }], 17 | "transform-es2015-parameters", 18 | ["transform-es2015-destructuring", { "loose": true }], 19 | "transform-es2015-block-scoping", 20 | "transform-es3-member-expression-literals", 21 | "transform-es3-property-literals", 22 | ], 23 | "env": { 24 | "commonjs": { 25 | "plugins": [ 26 | ["transform-es2015-modules-commonjs", { "loose": true }], 27 | ] 28 | }, 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /.eslintrc: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "eslint-config-airbnb", 3 | "env": { 4 | "mocha": true, 5 | "node": true 6 | }, 7 | "globals": { 8 | "expect": true 9 | }, 10 | "rules": { 11 | 'indent': [2, 4, { 'SwitchCase': 1, 'VariableDeclarator': 1 }], 12 | "padded-blocks": 0, 13 | "no-use-before-define": [2, "nofunc"], 14 | "no-unused-expressions": 0 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | node_modules 2 | coverage 3 | *.log 4 | lib 5 | dist 6 | es 7 | -------------------------------------------------------------------------------- /LICENSE.md: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2016 Zack Argyle 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | Redux Async Queue 2 | ============= 3 | 4 | Async queue [middleware](http://redux.js.org/docs/advanced/Middleware.html) for Redux. 5 | 6 | ``` 7 | npm install --save redux-async-queue 8 | ``` 9 | If you used ES modules 10 | ```js 11 | import ReduxAsyncQueue from 'redux-async-queue' // no changes here 😀 12 | ``` 13 | If you use CommonJS 14 | ```js 15 | var ReduxAsyncQueue = require('redux-async-queue').default 16 | ``` 17 | If you need a UMD version 18 | ```js 19 | var ReduxAsyncQueue = window.ReduxAsyncQueue.default 20 | ``` 21 | 22 | ## What is it? 23 | 24 | ReduxAsyncQueue [middleware](https://github.com/reactjs/redux/blob/master/docs/advanced/Middleware.md) makes queueing redux actions painless. This allows you to fire multiple actions simultaneously and have them execute asynchronously in order. 25 | 26 | The middleware will search for any action that has the `queue` property. It will then add the `callback` function to the corresponding queue. The `queue` key specifies to which queue this callback belongs. You may have several different queues for any given application. 27 | 28 | 29 | For example, let's say we are making burgers (because they're delicious!). We can only make one burger at a time, but our friends keep coming up and saying they want one. You have 10 requests, but can only make one at a time. Here is how we'd write that delicious example out with the ReduxAsyncQueue middleware. 30 | 31 | ```js 32 | // This is the name of the queue. This does not need to match the action 'type' in 'makeBurger()' 33 | // You could for example call this `MAKE_FOOD` if you were also going to be cooking up some 34 | // sweet potato fries and wanted them in the same queue even though they are different actions. 35 | const MAKE_BURGER = 'MAKE_BURGER'; 36 | 37 | function makeBurger(ingredients) { 38 | return { 39 | type: MAKE_BURGER, 40 | payload: ingredients, 41 | }; 42 | } 43 | 44 | function queueMakeBurger(burgerStyle) { 45 | return { 46 | queue: MAKE_BURGER, 47 | callback: (next, dispatch, getState) => { 48 | getIngredients(burgerStyle).then(ingredients => { 49 | dispatch(makeBurger(ingredients)); 50 | next(); 51 | }); 52 | } 53 | } 54 | } 55 | 56 | // Call the queue from your container / smart component 57 | dispatch(queueMakeBurger(burgerStyle)); 58 | ``` 59 | 60 | You'll notice the `next()` call within `callback`. That is the key to letting ReduxAsyncQueue know that you are ready to start making the next burger. If you do not call `next()` then the queue will not work. 61 | 62 | ## Installation 63 | ``` 64 | npm install --save redux-async-queue 65 | ``` 66 | 67 | To enable ReduxAsyncQueue, use [`applyMiddleware()`](http://redux.js.org/docs/api/applyMiddleware.html): 68 | 69 | ```js 70 | import { createStore, applyMiddleware } from 'redux'; 71 | import ReduxAsyncQueue from 'redux-async-queue'; 72 | import reducer from './reducers/index'; 73 | 74 | const store = createStore( 75 | reducer, 76 | applyMiddleware(ReduxAsyncQueue) 77 | ); 78 | ``` 79 | 80 | ## License 81 | 82 | MIT 83 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "redux-async-queue", 3 | "version": "1.0.0", 4 | "description": "Async queue middleware for Redux.", 5 | "main": "lib/index.js", 6 | "jsnext:main": "es/index.js", 7 | "files": [ 8 | "lib", 9 | "es", 10 | "src", 11 | "dist" 12 | ], 13 | "scripts": { 14 | "clean": "rimraf lib dist es", 15 | "build": "npm run build:commonjs && npm run build:umd && npm run build:umd:min && npm run build:es", 16 | "prepublish": "npm run clean && npm run test && npm run build", 17 | "posttest": "npm run lint", 18 | "lint": "eslint src test", 19 | "test": "cross-env BABEL_ENV=commonjs mocha --compilers js:babel-core/register --reporter spec test/*.js", 20 | "build:commonjs": "cross-env BABEL_ENV=commonjs babel src --out-dir lib", 21 | "build:es": "cross-env BABEL_ENV=es babel src --out-dir es", 22 | "build:umd": "cross-env BABEL_ENV=commonjs NODE_ENV=development webpack", 23 | "build:umd:min": "cross-env BABEL_ENV=commonjs NODE_ENV=production webpack" 24 | }, 25 | "repository": { 26 | "type": "git", 27 | "url": "https://github.com/zackargyle/redux-async-queue.git" 28 | }, 29 | "homepage": "https://github.com/zackargyle/redux-async-queue", 30 | "keywords": [ 31 | "redux", 32 | "queue", 33 | "middleware", 34 | "redux-middleware", 35 | "flux" 36 | ], 37 | "author": "Zack Argyle ", 38 | "license": "MIT", 39 | "devDependencies": { 40 | "babel-cli": "^6.6.5", 41 | "babel-core": "^6.6.5", 42 | "babel-eslint": "^5.0.0-beta4", 43 | "babel-loader": "^6.2.4", 44 | "babel-plugin-check-es2015-constants": "^6.6.5", 45 | "babel-plugin-transform-es2015-arrow-functions": "^6.5.2", 46 | "babel-plugin-transform-es2015-block-scoped-functions": "^6.6.5", 47 | "babel-plugin-transform-es2015-block-scoping": "^6.6.5", 48 | "babel-plugin-transform-es2015-classes": "^6.6.5", 49 | "babel-plugin-transform-es2015-computed-properties": "^6.6.5", 50 | "babel-plugin-transform-es2015-destructuring": "^6.6.5", 51 | "babel-plugin-transform-es2015-for-of": "^6.6.0", 52 | "babel-plugin-transform-es2015-function-name": "^6.5.0", 53 | "babel-plugin-transform-es2015-literals": "^6.5.0", 54 | "babel-plugin-transform-es2015-modules-commonjs": "^6.6.5", 55 | "babel-plugin-transform-es2015-object-super": "^6.6.5", 56 | "babel-plugin-transform-es2015-parameters": "^6.6.5", 57 | "babel-plugin-transform-es2015-shorthand-properties": "^6.5.0", 58 | "babel-plugin-transform-es2015-spread": "^6.6.5", 59 | "babel-plugin-transform-es2015-sticky-regex": "^6.5.0", 60 | "babel-plugin-transform-es2015-template-literals": "^6.6.5", 61 | "babel-plugin-transform-es2015-unicode-regex": "^6.5.0", 62 | "babel-plugin-transform-es3-member-expression-literals": "^6.5.0", 63 | "babel-plugin-transform-es3-property-literals": "^6.5.0", 64 | "chai": "^3.2.0", 65 | "cross-env": "^1.0.7", 66 | "eslint": "^1.10.2", 67 | "eslint-config-airbnb": "1.0.2", 68 | "eslint-plugin-react": "^4.1.0", 69 | "mocha": "^2.2.5", 70 | "rimraf": "^2.5.2", 71 | "webpack": "^1.12.14" 72 | } 73 | } 74 | -------------------------------------------------------------------------------- /src/index.js: -------------------------------------------------------------------------------- 1 | function assertFunc(fn, message) { 2 | if (typeof fn !== 'function') { 3 | throw message; 4 | } 5 | } 6 | 7 | export default function queueMiddleware({ dispatch, getState }) { 8 | const queues = {}; 9 | 10 | /** 11 | * This function executes the first function in 12 | * the queue at . It provides a param 13 | * to the queued function to notify when to dequeue 14 | * the next queued function. 15 | * 16 | * @param {string} key - the key for the particular queue 17 | * 18 | * Callback params 19 | * @param {Function} next - notify when async action is finished 20 | * @param {Function} dispatch - allow dispatching of more actions 21 | * @param {Function} getState - allow state use within callback 22 | */ 23 | function dequeue(key) { 24 | const callback = queues[key][0]; 25 | callback(function next() { 26 | queues[key].shift(); 27 | if (queues[key].length > 0) { 28 | dequeue(key); 29 | } 30 | }, dispatch, getState); 31 | } 32 | 33 | return next => action => { 34 | const { queue: key, callback } = action || {}; 35 | if (key) { 36 | assertFunc(callback, 'Queued actions must have a property'); 37 | // Verify array at 38 | queues[key] = queues[key] || []; 39 | // Add new queued callback 40 | queues[key].push(callback); 41 | // If it's the only one, sync call it. 42 | if (queues[key].length === 1) { 43 | dequeue(key); 44 | } 45 | } else { 46 | return next(action); 47 | } 48 | }; 49 | } 50 | -------------------------------------------------------------------------------- /test/index.js: -------------------------------------------------------------------------------- 1 | import chai from 'chai'; 2 | import queueMiddleware from '../src/index'; 3 | 4 | describe('queue middleware', () => { 5 | const doDispatch = () => {}; 6 | const doGetState = () => {}; 7 | const nextHandler = queueMiddleware({dispatch: doDispatch, getState: doGetState}); 8 | 9 | it('must return a function to handle next', () => { 10 | chai.assert.isFunction(nextHandler); 11 | chai.assert.strictEqual(nextHandler.length, 1); 12 | }); 13 | 14 | describe('handle action', () => { 15 | it('must run the given action function with next, dispatch and getState', done => { 16 | const actionHandler = nextHandler(); 17 | actionHandler({ 18 | queue: 'ARGUMENTS_TEST', 19 | callback: (next, dispatch, getState) => { 20 | chai.assert.isFunction(next); 21 | chai.assert.strictEqual(dispatch, doDispatch); 22 | chai.assert.strictEqual(getState, doGetState); 23 | done(); 24 | }, 25 | }); 26 | }); 27 | 28 | it('must pass action to next if no queue specified', done => { 29 | const actionObj = {}; 30 | 31 | const actionHandler = nextHandler(action => { 32 | chai.assert.strictEqual(action, actionObj); 33 | done(); 34 | }); 35 | 36 | actionHandler(actionObj); 37 | }); 38 | 39 | it('must return the return value of next if not a function', () => { 40 | const expected = 'redux'; 41 | const actionHandler = nextHandler(() => expected); 42 | 43 | const outcome = actionHandler(); 44 | chai.assert.strictEqual(outcome, expected); 45 | }); 46 | 47 | it('must be invoked synchronously if queue is empty', () => { 48 | const actionHandler = nextHandler(); 49 | let mutated = 0; 50 | 51 | actionHandler({ 52 | queue: 'SYNC_TEST', 53 | callback: () => mutated++, 54 | }); 55 | chai.assert.strictEqual(mutated, 1); 56 | }); 57 | 58 | it('must be invoked asynchronously if queue is not empty', done => { 59 | const actionHandler = nextHandler(); 60 | let mutated = 0; 61 | 62 | actionHandler({ 63 | queue: 'ASYNC_TEST', 64 | callback: next => setTimeout(next, 0), 65 | }); 66 | 67 | actionHandler({ 68 | queue: 'ASYNC_TEST', 69 | callback: next => ++mutated && next(), 70 | }); 71 | 72 | actionHandler({ 73 | queue: 'ASYNC_TEST', 74 | callback: next => { 75 | chai.assert.strictEqual(mutated, 1); 76 | next(); 77 | done(); 78 | }, 79 | }); 80 | chai.assert.strictEqual(mutated, 0); 81 | }); 82 | }); 83 | 84 | describe('handle errors', () => { 85 | it('must throw if argument is non-object', done => { 86 | try { 87 | queueMiddleware(); 88 | } catch (err) { 89 | done(); 90 | } 91 | }); 92 | 93 | it('must throw if callback is non-function', done => { 94 | const actionHandler = nextHandler(); 95 | try { 96 | actionHandler({ 97 | queue: 'CALLBACK_ERROR_TEST', 98 | }); 99 | } catch (err) { 100 | done(); 101 | } 102 | }); 103 | }); 104 | }); 105 | -------------------------------------------------------------------------------- /webpack.config.babel.js: -------------------------------------------------------------------------------- 1 | import webpack from 'webpack'; 2 | import path from 'path'; 3 | 4 | const { NODE_ENV } = process.env; 5 | 6 | const plugins = [ 7 | new webpack.optimize.OccurenceOrderPlugin(), 8 | new webpack.DefinePlugin({ 9 | 'process.env.NODE_ENV': JSON.stringify(NODE_ENV), 10 | }), 11 | ]; 12 | 13 | const filename = `redux-async-queue${NODE_ENV === 'production' ? '.min' : ''}.js`; 14 | 15 | NODE_ENV === 'production' && plugins.push( 16 | new webpack.optimize.UglifyJsPlugin({ 17 | compressor: { 18 | pure_getters: true, 19 | unsafe: true, 20 | unsafe_comps: true, 21 | screw_ie8: true, 22 | warnings: false, 23 | }, 24 | }) 25 | ); 26 | 27 | export default { 28 | module: { 29 | loaders: [ 30 | { test: /\.js$/, loaders: ['babel-loader'], exclude: /node_modules/ }, 31 | ], 32 | }, 33 | 34 | entry: [ 35 | './src/index', 36 | ], 37 | 38 | output: { 39 | path: path.join(__dirname, 'dist'), 40 | filename, 41 | library: 'ReduxAsyncQueue', 42 | libraryTarget: 'umd', 43 | }, 44 | 45 | plugins, 46 | }; 47 | --------------------------------------------------------------------------------