Repository: ericelliott/redux-dsm Branch: master Commit: 0fbf674da099 Files: 15 Total size: 21.3 KB Directory structure: gitextract_i2v1ru16/ ├── .eslintignore ├── .eslintrc ├── .gitignore ├── .npmignore ├── .snyk ├── .travis.yml ├── LICENSE ├── README.md ├── package.json ├── renovate.json ├── source/ │ ├── dsm.js │ └── test/ │ ├── authenticate-flow-test.js │ ├── index.js │ └── test.js └── tools/ └── cli.js ================================================ FILE CONTENTS ================================================ ================================================ FILE: .eslintignore ================================================ distribution ================================================ FILE: .eslintrc ================================================ { "parserOptions": { "sourceType": "module", "ecmaVersion": 8, "ecmaFeatures": { "blockBindings": true, "jsx": true, "modules": true } }, "env": { "browser": true, "es6": true, "jasmine": true, "node": true }, "rules": { "arrow-spacing": 2, "brace-style": 2, "camelcase": 2, "comma-dangle": [ 2, "never" ], "comma-spacing": [ 2, { "before": false, "after": true } ], "comma-style": [ 2, "last" ], "complexity": [ 1, 8 ], "consistent-this": [ 2, "_this" ], "default-case": 2, "dot-notation": 2, "eol-last": 2, "eqeqeq": 2, "guard-for-in": 1, "indent": [ 2, 2, { "SwitchCase": 1 } ], "key-spacing": [ 2, { "beforeColon": false, "afterColon": true } ], "keyword-spacing": [ 1, { "before": true, "after": true } ], "new-cap": 2, "new-parens": 2, "no-caller": 2, "no-debugger": 1, "no-dupe-args": 2, "no-dupe-keys": 2, "no-dupe-class-members": 2, "no-duplicate-case": 2, "no-eq-null": 0, "no-eval": 2, "no-implied-eval": 2, "no-invalid-regexp": 2, "no-mixed-spaces-and-tabs": 2, "no-redeclare": 2, "no-self-compare": 1, "no-shadow-restricted-names": 2, "no-trailing-spaces": 2, "no-undef": 2, "no-undef-init": 2, "no-underscore-dangle": 0, "no-unreachable": 2, "no-unused-vars": 1, "no-use-before-define": 2, "no-with": 2, # "no-magic-numbers": 1, "one-var": [ 2, "never" ], "operator-assignment": [ 2, "always" ], "quote-props": 0, "quotes": [ 2, "single" ], "radix": 2, "semi": [ 2, "always" ], "semi-spacing": [ 2, { "before": false, "after": true } ], "sort-vars": [ 1, { "ignoreCase": true } ], "space-before-function-paren": [ 2, { "anonymous": "always", "named": "never" } ], "space-in-parens": [ 2, "never" ], "space-infix-ops": 2, "space-unary-ops": [ 2, { "words": true, "nonwords": false } ], "strict": [ 2, "global" ], "use-isnan": 2, "valid-jsdoc": 1, "yoda": [ 2, "never", { "exceptRange": false } ] } } ================================================ FILE: .gitignore ================================================ .DS_Store node_modules npm-debug.log distribution ================================================ FILE: .npmignore ================================================ source ================================================ FILE: .snyk ================================================ # Snyk (https://snyk.io) policy file, patches or ignores known vulnerabilities. version: v1.10.1 ignore: {} patch: {} ================================================ FILE: .travis.yml ================================================ language: node_js node_js: - "8" ================================================ FILE: LICENSE ================================================ MIT License Copyright (c) 2016 Eric Elliott Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ================================================ FILE: README.md ================================================ # Redux DSM Declarative State Machines for Redux: Reduce your async-state boilerplate. Redux-dsm takes a nested array of transitions and states and automatically generates: * Reducers to manage all state transitions, complete with logic that will not let your app get into an invalid state (according to the graph you supply) * Action creators and action types to trigger all transitions ## Status In production use on [DevAnywhere.io](https://devanywhere.io). ## Install ```sh npm install --save redux-dsm ``` And then in your file : ```js import dsm from 'redux-dsm'; ``` Or using CommonJS modules : ```js var dsm = require('redux-dsm'); ``` ## Why? Your state isn't always available synchronously all the time. Some state has to be loaded asynchronously, which requires you to cycle through UI states representing concepts like fetching, processing, error, success, and idle states. In fact, a simple ajax fetch might have up to 7 transitions leading into 4 different states: ``` Transition Next Status ['initial', 'idle'] ['fetch', 'fetching'] ['cancel', 'idle'] ['report error', 'error'] ['handle error', 'idle'] ['report success', 'success'] ['handle success', 'idle'] ``` Your view code will look at the status and payload to determine whether or not to render spinners, success messages, error messages, empty states, or data. I don't know about you, but I sometimes forget some of those transitions or states. Every app I've ever written needs to do this a bunch of times. Since I switched to Redux, I handle all of my view state transitions by dispatching action objects, and that requires writing a bunch of boilerplate, such as action types (e.g., `myComponent::FETCH_FOO::FETCH`), and action creators (which your view or service layers can call to create actions without forcing you to import all those action type constants everywhere). This little library takes a few declarative inputs and spits out all of the boilerplate for you, including a mini reducer that you can combine with your feature-level reducers. ## Can I Use it With *x*? This library is not just for ajax, though that will be a very common use-case, and it doesn't care how you handle your async I/O. You can use it with [Sagas](https://github.com/yelouafi/redux-saga), redux-thunks, action creators with side-effects, etc..., or just use it by itself and manually wire up your async I/O. You don't even have to use it with Redux -- anything that uses reducer-based state is fine, including [ngrx/store](https://github.com/ngrx/store) or even `Array.prototype.reduce()`. ## Usage Example ```js import dsm from 'redux-dsm'; // ['action', 'next state', // ['scoped action', 'another state'] // ] // e.g., in the following example, from 'fetching' state, we can: // * cancel // * report an error // * report success const fetchingStates = ['initial', 'idle', ['fetch', 'fetching', ['cancel', 'idle'], ['report error', 'error', ['handle error', 'idle'] ], ['report success', 'success', ['handle success', 'idle'] ] ] ]; // ({ // component?: String, // description?: String, // actionStates: Array, // delimiter?: String // }) => { actions: Object, actionCreators: Object, reducer: Function } const foo = dsm({ component: 'myComponent', description: 'fetch foo', actionStates: fetchingStates }); ``` ## .actions: Object `actions` is an object with camelCased keys and strings corresponding to your state transitions. If you use the returned `.actionCreators`, you probably don't need to use these, but it's handy for debugging. For the above example, it returns: ```js "actions": { "fetch": "myComponent::FETCH_FOO::FETCH", "cancel": "myComponent::FETCH_FOO::CANCEL", "reportError": "myComponent::FETCH_FOO::REPORT_ERROR", "handleError": "myComponent::FETCH_FOO::HANDLE_ERROR", "reportSuccess": "myComponent::FETCH_FOO::REPORT_SUCCESS", "handleSuccess": "myComponent::FETCH_FOO::HANDLE_SUCCESS" } ``` ## .actionCreators: Object `actionCreators` will be an object with camelCased keys and function values corresponding to your state transitions. For each transition, an action creator is created which will automatically fill in the correct action type, and pass through `payload` to the state. The example fetch state machine will produce the following `actionCreators`: ```js fetch() cancel() reportError() handleError() reportSuccess() handleSuccess() ``` ## .reducer: (state, action) => state `.reducer()` is a normal Redux reducer function that takes the current state and an action object, and returns the new state. Matching action objects can be created using the `.actionCreators`. The reducer can be combined with a parent reducer using `combineReducers()`. Any payload passed into an action creator will be passed through to `state.payload`. ## State: { status: String, payload: Any } The state object will have two keys, `status` and `payload`. In the example above, `status` will be one of `idle`, `fetching`, `error`, or `success`. By default, the `payload` key is an object with `type: 'empty'`. ================================================ FILE: package.json ================================================ { "name": "redux-dsm", "version": "3.0.3", "description": "Declarative State Machines for Redux", "main": "./distribution/dsm.js", "directories": { "doc": "docs" }, "scripts": { "lint": "eslint . && echo 'Lint finished...\n'", "posttest": "npm run -s lint && node tools/cli.js", "test": "node -r @std/esm source/test/index.js && node -r @std/esm source/test/authenticate-flow-test.js", "debug": "node -r @std/esm --inspect-brk source/test/test.js", "watch": "watch 'clear && npm run -s test' source", "update": "updtr", "build": "babel source --presets babel-preset-es2015 --out-dir distribution", "prepublish": "npm run build" }, "@std/esm": "cjs", "repository": { "type": "git", "url": "git+https://github.com/ericelliott/redux-dsm.git" }, "keywords": [ "state", "machine", "redux" ], "author": "Eric Elliott", "license": "MIT", "bugs": { "url": "https://github.com/ericelliott/redux-dsm/issues" }, "homepage": "https://github.com/ericelliott/redux-dsm#readme", "engines": { "node": ">=6.0.0" }, "devDependencies": { "@std/esm": "0.26.0", "babel-cli": "6.26.0", "babel-preset-es2015": "6.24.1", "colors": "1.3.2", "eslint": "5.6.1", "lodash": "4.17.11", "riteway": "3.0.0", "snyk": "1.101.1", "tape": "4.9.1", "updtr": "3.1.0", "watch": "1.0.2" }, "dependencies": { "lodash.camelcase": "4.3.0", "lodash.snakecase": "4.1.1" } } ================================================ FILE: renovate.json ================================================ { "extends": [ "config:base" ], "automerge": true, "major": { "automerge": false } } ================================================ FILE: source/dsm.js ================================================ const camelCase = require('lodash.camelcase'); const snakeCase = require('lodash.snakecase'); const defaultStatus = 'idle'; const parseNode = node => { const data = node.slice(0, 2); const child = node.slice(2); return { data, child }; }; const getDefaultStatus = (actionStates) => { const status = actionStates[1]; return status ? status : defaultStatus; }; const getStates = (graph, initialMemo = [], parentStatus) => ( graph.reduce((memo, node) => { const { data, child } = parseNode(node); if (Array.isArray(data)) memo = memo.concat([data.concat([parentStatus])]); if (Array.isArray(child)) memo = getStates(child, memo, data[1]); return memo; }, initialMemo) ); const formatConstant = text => snakeCase(text).toUpperCase(); const empty = { type: 'empty' }; const composeReducers = (...reducers) => reducers.reduce((step, reducer) => (a, c) => step(reducer(a, c), c)); const createReducer = (defaultState, reducerMap) => { return (state = defaultState, action = {}) => { const { type } = action; const reducer = Array.isArray(reducerMap[type]) ? composeReducers(...reducerMap[type]) : state => state ; return reducer(state, action); }; }; const getActionCreatorNames = states => { return states.map(state => { const description = state[0]; return camelCase(description); }); }; const dsm = ({ component = '', description = '', delimiter = '::', actionStates = [] }) => { const defaultState = { status: getDefaultStatus(actionStates), payload: empty }; const states = [...getStates(actionStates, [], defaultState.status)]; const actionNames = getActionCreatorNames(states); const actionMap = states.map(a => { const action = component + [ component ? delimiter : '', formatConstant(description), description ? delimiter : '', formatConstant(a[0]) ].join(''); const status = a[1]; const parentStatus = a[2]; return { action, status, parentStatus }; }); const actions = actionMap.map(a => a.action).reduce((acs, action, i) => { acs[actionNames[i]] = action; return acs; }, {}); const reducerMap = actionMap.reduce((map, a) => { const reducer = (state = defaultState, action = {}) => { if (state.status === a.parentStatus && action.type === a.action) { const { status } = a; const { payload } = action; return Object.assign({}, state, { status, payload }); } return state; }; if (!map[a.action]) map[a.action] = [reducer]; else map[a.action].push(reducer); return map; }, {}); const reducer = createReducer(defaultState, reducerMap); const actionCreators = actionNames.reduce((acs, description) => { acs[description] = payload => ({ type: actions[description], payload }); return acs; }, {}); return { actions, actionCreators, reducer }; }; module.exports = dsm; module.exports.dsm = dsm; module.exports.default = dsm; ================================================ FILE: source/test/authenticate-flow-test.js ================================================ import { describe } from 'riteway'; import dsm from '../dsm'; const SIGNED_OUT = 'signed out'; const AUTHENTICATING = 'authenticating'; const ERROR = 'error'; const SIGNED_IN = 'signed in'; const actionStates = ['initial', SIGNED_OUT, ['sign in', AUTHENTICATING, ['report sign in failure', ERROR, ['handle sign in failure', SIGNED_OUT] ], ['report sign in success', SIGNED_IN, ['sign out', SIGNED_OUT] ] ], ['report sign in success', SIGNED_IN, ['sign out', SIGNED_OUT] ] ]; const { reducer, actionCreators: { signIn, reportSignInSuccess } } = dsm({ component: 'user-authentication', description: 'authenticate user', actionStates }); describe('userAuthenticationReducer', async assert => { { const should = 'use "signed out" as initialized state'; assert({ given: '["initial", "signed out", /*...*/', should, actual: reducer().status, expected: SIGNED_OUT }); } { const should = 'transition into authenticating state'; assert({ given: 'signed out initial state & signIn action', should, actual: reducer(undefined, signIn()).status, expected: AUTHENTICATING }); } { const should = 'transition into "signed in" state'; const initialState = reducer(undefined, signIn()); assert({ given: '"authenticating" initial state & reportSignInSuccess action', should, actual: reducer(initialState, reportSignInSuccess()).status, expected: SIGNED_IN }); } { const should = 'transition into "signed in" state'; assert({ given: '"signed out" initial state & reportSignInSuccess action', should, actual: reducer(undefined, reportSignInSuccess()).status, expected: SIGNED_IN }); } }); ================================================ FILE: source/test/index.js ================================================ import './test'; ================================================ FILE: source/test/test.js ================================================ const test = require('tape'); const lodash = require('lodash'); const pipe = lodash.flow; const dsm = require('../dsm'); const createFlatStates = () => ['initial', 'idle', ['fetch', 'fetching'], ['cancel', 'idle'], ['report error', 'error'], ['handle error', 'idle'], ['report success', 'success'], ['handle success', 'idle'] ]; const mockStates = ['initial', 'idle', ['fetch', 'fetching', ['cancel', 'idle'], ['report error', 'error', ['handle error', 'idle'] ], ['report success', 'success', ['handle success', 'idle'] ] ] ]; const mockOptions = ({ component = 'myComponent', description = 'fetch foo', actionStates = mockStates } = {}) => ({ component, description, actionStates }); test('modules & package specs', nest => { nest.test('dsm function exposed', assert => { const msg = 'should export commonjs module'; const expected = 'function'; const actual = typeof require('../dsm'); assert.same(actual, expected, msg); assert.end(); }); nest.test('dsm object exposed', assert => { const msg = 'should export dsm property allowing `import { dsm }`'; const expected = 'function'; const actual = typeof require('../dsm').dsm; assert.same(actual, expected, msg); assert.end(); }); }); test('dsm() action types', nest => { nest.test('flat state', assert => { const msg = 'should return action types corresponding with given transitions'; const expected = { fetch: 'myComponent::FETCH_FOO::FETCH', cancel: 'myComponent::FETCH_FOO::CANCEL', reportError: 'myComponent::FETCH_FOO::REPORT_ERROR', handleError: 'myComponent::FETCH_FOO::HANDLE_ERROR', reportSuccess: 'myComponent::FETCH_FOO::REPORT_SUCCESS', handleSuccess: 'myComponent::FETCH_FOO::HANDLE_SUCCESS' }; const actual = dsm(mockOptions({ actionStates: createFlatStates() })).actions; assert.same(actual, expected, msg); assert.end(); }); nest.test('nested state', assert => { const msg = 'should return action types corresponding with given transitions'; const expected = { fetch: 'myComponent::FETCH_FOO::FETCH', cancel: 'myComponent::FETCH_FOO::CANCEL', reportError: 'myComponent::FETCH_FOO::REPORT_ERROR', handleError: 'myComponent::FETCH_FOO::HANDLE_ERROR', reportSuccess: 'myComponent::FETCH_FOO::REPORT_SUCCESS', handleSuccess: 'myComponent::FETCH_FOO::HANDLE_SUCCESS' }; const actual = dsm(mockOptions()).actions; assert.same(actual, expected, msg); assert.end(); }); }); test('dsm() reducer', nest => { nest.test('with unrestricted state', assert => { const msg = 'should transition to correct state'; const action = { type: 'myComponent::FETCH_FOO::FETCH' }; const reducer = dsm(mockOptions({ actionStates: createFlatStates() })).reducer; const actual = reducer(undefined, action).status; const expected = 'fetching'; assert.same(actual, expected, msg); assert.end(); }); nest.test('with unrestricted state', assert => { const msg = 'should deliver correct payload'; const payload = { type: 'response', data: 'some data' }; const action = { type: 'myComponent::FETCH_FOO::REPORT_SUCCESS', payload }; const reducer = dsm(mockOptions({ actionStates: createFlatStates() })).reducer; const actual = reducer(undefined, action); const expected = { status: 'success', payload }; assert.same(actual, expected, msg); assert.end(); }); nest.test('with nested state', assert => { const msg = 'should transition to correct state'; const action = { type: 'myComponent::FETCH_FOO::FETCH' }; const reducer = dsm(mockOptions()).reducer; const actual = reducer(undefined, action).status; const expected = 'fetching'; assert.same(actual, expected, msg); assert.end(); }); nest.test('with nested state', assert => { const msg = 'should ignore invalid action for current state'; const action = { type: 'myComponent::FETCH_FOO::REPORT_ERROR' }; const reducer = dsm(mockOptions()).reducer; const actual = reducer(undefined, action).status; const expected = 'idle'; assert.same(actual, expected, msg); assert.end(); }); }); test('action creators', nest => { nest.test('names', assert => { const msg = 'should return action creators with correct names'; const expected = [ 'fetch', 'cancel', 'reportError', 'handleError', 'reportSuccess', 'handleSuccess' ]; const pipeline = pipe( dsm, obj => obj.actionCreators, Object.keys ); const actual = pipeline(mockOptions({ actionStates: createFlatStates() })); assert.same(actual, expected, msg); assert.end(); }); nest.test('functions', assert => { const msg = 'should return correct actions'; const payload = 'some data'; const expected = { type: 'myComponent::FETCH_FOO::REPORT_SUCCESS', payload }; const pipeline = pipe( dsm, obj => obj.actionCreators.reportSuccess(payload) ); const actual = pipeline(mockOptions({ actionStates: createFlatStates() })); assert.same(actual, expected, msg); assert.end(); }); nest.test('payloads', assert => { const msg = 'new state should reflect action payloads'; const payload = 'some data'; const request = dsm(mockOptions({ actionStates: createFlatStates() })); const action = request.actionCreators.reportSuccess(payload); const actual = request.reducer(undefined, action); const expected = { status: 'success', payload }; assert.same(actual, expected, msg); assert.end(); }); }); ================================================ FILE: tools/cli.js ================================================ require('colors'); /** * Checks node version and prints a message before tests start * Latest Nodejs or at least 6.x.x is required to run our ES6 tests * @param {String} nodeVersion node semantic version * @returns {undefined} */ function checkNode(nodeVersion) { if (Number(nodeVersion.slice('.')[0]) < 8) { console.log('Tests require Node version > v8.0.0 to run'.red); } } module.exports = checkNode(process.versions.node);