@budarin/redux-business-logic-middleare
TypeScript icon, indicating that this package has built-in type declarations

2.1.11 • Public • Published

redux-business-logic-middleare

Middleware for processing business login in redux application.

Instllation

Using npm

npm install --save-dev @budarin/redux-business-logic-middleare

Using yarn

yarn add -D @budarin/redux-business-logic-middleare

Using:

Let's implement a simple business rule for Todo: “when creating a todo, send the todo to the server and to the redux store”.

Let's describe the essence of Todo — its constants, actions, business rules and a redeser in accordance with the concept of ducks.

./ducks/todo.js

import { sendTodo } from 'src/services/api'
import { onAction } from'@budarin/redux-business-logic-middleare';

const SET_ERROR = 'TODO/SET_ERROR';
export const ADD_TODO = 'TODO/ADD_TODO';

export const setError = (error) => ({
    type: SET_ERROR,
    payload: error
})

export const addTodo = ( todo ) => ({
    type: ADD_TODO,
    payload: todo 
});

// our business rule
export const addTodoMiddleware = async (store, next, action) => {
    // call the API method to send todo to the server
    try {
        await sendTodo(action.payload);
    } catch(error) {
        return store.dispatch(setError(error));
    }

     // otherwise, we pass the action to the next middleware
    return next(action);
}

// let's add the business rule
onAction(ADD_TODO, addTodoMiddleware)


export default const reducer = (state = initialState, action) => {
    switch (action.type) {
        case ADD_TODO: {
            ...
        }
        case SET_ERROR {
            ...
        }
        default:
            return state;
    }
};

Add midleware to stores middlewares

import todoReducer from '../ducks/todo.js'
import { createStore, applyMiddleware, combineReducers } from 'redux'
import { bussinesLogicMiddleware } from '@budarin/redux-business-logic-middleare';

const reducers = combineReducers(
    ...
    todoReducer,
    ...
);

const store = createStore(
    reducers, 
    initialState, 
    applyMiddleware(bussinesLogicMiddleware)
);

To remove bussines-rule from processing

import { ADD_TODO } from '../ducks/todo.js'
import { offAction } from '@budarin/redux-business-logic-middleare';

offAction(ADD_TODO);

To remove all bussines-rules from processing

import { removeAllBusinessRules } from '@budarin/redux-business-logic-middleare';

removeAllBusinessRules();

Package Sidebar

Install

npm i @budarin/redux-business-logic-middleare

Weekly Downloads

0

Version

2.1.11

License

MIT

Unpacked Size

12.8 kB

Total Files

10

Last publish

Collaborators

  • budarin