create-store.js (2796B)
1 /* This Source Code Form is subject to the terms of the Mozilla Public 2 * License, v. 2.0. If a copy of the MPL was not distributed with this 3 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ 4 "use strict"; 5 6 const { 7 combineReducers, 8 createStore, 9 applyMiddleware, 10 } = require("resource://devtools/client/shared/vendor/redux.js"); 11 12 const { 13 ignore, 14 } = require("resource://devtools/client/shared/redux/middleware/ignore.js"); 15 const { 16 promise, 17 } = require("resource://devtools/client/shared/redux/middleware/promise.js"); 18 const { 19 task, 20 } = require("resource://devtools/client/shared/redux/middleware/task.js"); 21 const { 22 thunk, 23 } = require("resource://devtools/client/shared/redux/middleware/thunk.js"); 24 const { 25 waitUntilService, 26 } = require("resource://devtools/client/shared/redux/middleware/wait-service.js"); 27 28 const flags = require("resource://devtools/shared/flags.js"); 29 30 loader.lazyRequireGetter( 31 this, 32 "log", 33 "resource://devtools/client/shared/redux/middleware/log.js", 34 true 35 ); 36 37 /** 38 * This creates a dispatcher with all the standard middleware in place 39 * that all code requires. It can also be optionally configured in 40 * various ways, such as logging and recording. 41 * 42 * @param {object} opts: 43 * - enableTaskMiddleware: if true, include the task middleware 44 * - log: log all dispatched actions to console 45 * - middleware: array of middleware to be included in the redux store 46 * - thunkOptions: object that will be spread within a {dispatch, getState} object, 47 * that will be passed in each thunk action. 48 */ 49 const createStoreWithMiddleware = (opts = {}) => { 50 const middleware = [ 51 // Ignore should be registered first to prevent any subsequent middle from running 52 ignore, 53 ]; 54 if (opts.enableTaskMiddleware) { 55 middleware.push(task); 56 } 57 middleware.push( 58 thunk(opts.thunkOptions), 59 promise, 60 61 // Order is important: services must go last as they always 62 // operate on "already transformed" actions. Actions going through 63 // them shouldn't have any special fields like promises, they 64 // should just be normal JSON objects. 65 waitUntilService 66 ); 67 68 if (opts.middleware) { 69 opts.middleware.forEach(fn => middleware.push(fn)); 70 } 71 72 if (opts.log) { 73 middleware.push(log); 74 } 75 76 return applyMiddleware(...middleware)(createStore); 77 }; 78 79 module.exports = ( 80 reducers, 81 { 82 shouldLog = false, 83 initialState = undefined, 84 thunkOptions, 85 enableTaskMiddleware = false, 86 } = {} 87 ) => { 88 const reducer = 89 typeof reducers === "function" ? reducers : combineReducers(reducers); 90 91 const store = createStoreWithMiddleware({ 92 enableTaskMiddleware, 93 log: flags.testing && shouldLog, 94 thunkOptions, 95 })(reducer, initialState); 96 97 return store; 98 };