redux-modern-crud v2.1.1
redux-modern-crud
A library that helps you to manage CRUD for Redux.
This library was generated by essay(https://github.com/dtinth/essay).
Inspiration
I used react-redux-universal-hot-example, and I would like to handle CRUD with easier way.
I saw app structure of bemuse, and it is easy to test and handling about redux.
Restructure
actionscontains constant of action types.entitiescontains core functions for handle states.interactorscontains the functions for dispatch action, it is useful withreact-redux.reducersmanages the store and calls the correct entity when receive action type.
├── README.md
└── src
├── interactors.js
└── redux
├── actions
│ ├── index.js
│ └── sample.js
├── entities
│ ├── index.js
│ ├── sample.js
│ └── sample.unit.spec.js
├── interactors
│ ├── index.js
│ └── sample.js
└── reducers
├── index.js
└── sample.js
└── sample.integration.spec.jsGetting started
Install this library
npm i --save redux-modern-crudimport module from this library
import { utility, createActions, createReducer, createInteractor, mergeReducer } from 'redux-modern-crud'
API
There are available modules that you can use.
// main.js
import * as utility from './utility';
export { utility };
export { createActions } from './create-actions';
export { createReducer } from './create-reducer';
export { createInteractor } from './create-interactor';
export { mergeReducer } from './merge-reducer';Implementation
It shows inside this module how it works.
Create Actions
createActions is a module that create three action types of CRUD.
REQUESTstarting request and waiting for responseSUCCESSAPI respond status 200 and bodyFAILAPI respond error with some reasons
// create-actions.js
import { getActionTypes } from './utility';
export const createActions = (prefix, key) => {
const [REQUEST, SUCCESS, FAIL] = getActionTypes(prefix, key);
return { REQUEST, SUCCESS, FAIL };
};Create Reducer
createReducer is a module that create a pure function for handle CRUD state of redux.
It will call a specific entity follow action type that is similar switch case.
- Using
redux-actionsfor create a simple reducer createReducerhas callback functions options (e.g. use for handle access-token)
// create-reducer.js
import { handleActions } from 'redux-actions';
import { handleWaiting, handleSuccess, handleFail, initState } from './entity';
const initialState = initState();
const initialAction = { type: 'init action' };
const defaultCallback = {
callbackWaiting: () => {},
callbackSuccess: () => {},
callbackFail: () => {},
};
export const createReducer = (actions, multipleCallback) => {
const { callbackWaiting, callbackSuccess, callbackFail } = {
...defaultCallback, ...multipleCallback
};
const { REQUEST, SUCCESS, FAIL } = actions;
const reducer = handleActions({
[REQUEST]: (state, action) => {
callbackWaiting(state, action);
return handleWaiting()(state);
},
[SUCCESS]: (state, action) => {
callbackSuccess(state, action);
return handleSuccess(action.result)(state);
},
[FAIL]: (state, action) => {
callbackFail(state, action);
return handleFail(action.error)(state);
}
}, initialState);
return reducer;
};Entity
entity contains the core functions that handle about state.
// entity.js
export const isInitialState = (state) => !state.request && !state.success;
export const isWaiting = (state) => state.waiting;
export const isSuccess = (state) => state.success && !!state.result;
export const isFailure = (state) => !!state.error;
export function initState() {
return { waiting: false, success: false };
}
export const handleWaiting = () => (state) => ({
...state,
waiting: true
});
export const handleSuccess = (result) => (state) => ({
...state,
waiting: false,
success: true,
error: null,
result
});
export const handleFail = (error) => (state) => ({
...state,
waiting: false,
success: false,
error
});Testing
entity.test uses circumstance
to test the entities with given, when, and then.
// entity.test.js
import { given, shouldEqual } from 'circumstance';
import * as CRUD from './entity';
describe('CRUD Entity', () => {
it('should init state', () => {
given(CRUD.initState())
.then(CRUD.isInitialState, shouldEqual(true));
});
it('should handle waiting state', () => {
given(CRUD.initState())
.when(CRUD.handleWaiting())
.then(CRUD.isWaiting, shouldEqual(true));
});
it('should handle success state', () => {
given(CRUD.initState())
.when(CRUD.handleSuccess('Operation Success'))
.then(CRUD.isSuccess, shouldEqual(true));
});
it('should handle fail state', () => {
given(CRUD.initState())
.when(CRUD.handleFail('has some exceptions'))
.then(CRUD.isFailure, shouldEqual(true));
});
});Create Interactor
createInteractor can create a function that helps you to dispatch action with http request and return promise.
// create-interactor.js
export const createInteractor = (actions) => {
const { REQUEST, SUCCESS, FAIL } = actions;
const formRequest = (method) => (url, { data, params } = {}) => ({
types: [REQUEST, SUCCESS, FAIL],
promise: (client) => client[method](url, { data, params })
});
const httpRequest = {};
const methods = ['get', 'put', 'post', 'del', 'patch'];
methods.map((method) => {
return httpRequest[method] = formRequest(method);
});
return httpRequest;
};Merge Reducer
mergeReducer merges all of them into one reducer. It selects action types by containing keyword.
mergeReducer is difference from combineReducers because
combineReducershelps you to keep the same logical division between reducers. http://redux.js.org/docs/api/combineReducers.html
// merge-reducer.js
import _ from 'lodash';
import { initState } from './entity';
const initialState = initState();
export const mergeReducer = (multiReducers) => {
const reducer = (state = initialState, action = initialAction) => {
const found = _.find(multiReducers, ({ word, reducer }) => {
return action.type.indexOf(word) !== -1;
});
if (!!found) {
return found.reducer(state, action);
}
return state;
};
return reducer;
};Utility
addPrefix generates a simple accessible action types of object that can be called by dot.
- e.g. UserActions.LOGIN.SUCCESS
getActionTypes generates an array that contains three action types of CRUD.
// utility.js
import _ from 'lodash';
export const addPrefix = (prefix, asyncKeys, syncKeys) => {
return _.fromPairs(
asyncKeys.map(asyncKey => {
return [(asyncKey || []), {
REQUEST: `${prefix}/${asyncKey}_REQUEST`,
SUCCESS: `${prefix}/${asyncKey}_SUCCESS`,
FAIL: `${prefix}/${asyncKey}_FAIL`
}];
}).concat((syncKeys || []).map(syncKey => {
return [syncKey, `${prefix}/${syncKey}`];
}))
);
};
export const getActionTypes = (prefix, key) => {
return [
`${prefix}/${key}_REQUEST`,
`${prefix}/${key}_SUCCESS`,
`${prefix}/${key}_FAIL`
];
};Testing
utility.test uses chai to test the utility with function expect.
// utility.test.js
import { expect } from 'chai';
import { addPrefix, getActionTypes } from './utility';
describe('Utility', () => {
describe('addPrefix', () => {
it('should return correct action types when pass prefix and asyncKeys', () => {
const actualResult = addPrefix('A', ['X', 'Y']);
const expectedResult = {
X: {
REQUEST: 'A/X_REQUEST',
SUCCESS: 'A/X_SUCCESS',
FAIL: 'A/X_FAIL'
},
Y: {
REQUEST: 'A/Y_REQUEST',
SUCCESS: 'A/Y_SUCCESS',
FAIL: 'A/Y_FAIL'
}
};
expect(actualResult).to.eql(expectedResult);
})
it('should return correct action types when pass prefix and syncKeys', () => {
const actualResult = addPrefix('A', [], ['X', 'Y']);
const expectedResult = { X: 'A/X', Y: 'A/Y' };
expect(actualResult).to.eql(expectedResult);
})
it('should return correct action types when pass prefix, asyncKeys and syncKeys', () => {
const actualResult = addPrefix('A', ['U', 'V'], ['X', 'Y', 'Z']);
const expectedResult = {
U: {
REQUEST: 'A/U_REQUEST',
SUCCESS: 'A/U_SUCCESS',
FAIL: 'A/U_FAIL'
},
V: {
REQUEST: 'A/V_REQUEST',
SUCCESS: 'A/V_SUCCESS',
FAIL: 'A/V_FAIL'
},
X: 'A/X',
Y: 'A/Y',
Z: 'A/Z'
};
expect(actualResult).to.eql(expectedResult);
})
});
describe('getActionTypes', () => {
it('should return correct action types when pass prefix and key', () => {
const actualResult = getActionTypes('USER', 'LOGIN');
const expectedResult = ['USER/LOGIN_REQUEST', 'USER/LOGIN_SUCCESS', 'USER/LOGIN_FAIL'];
expect(actualResult).to.eql(expectedResult);
});
});
});