npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

redux-modern-crud

v2.1.1

Published

A library that helps you to manage `CRUD` for `Redux`.

Downloads

17

Readme

redux-modern-crud

NPM version Build status

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

  • actions contains constant of action types.
  • entities contains core functions for handle states.
  • interactors contains the functions for dispatch action, it is useful with react-redux.
  • reducers manages 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.js

Getting started

  1. Install this library
npm i --save redux-modern-crud
  1. import 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.

  • REQUEST starting request and waiting for response
  • SUCCESS API respond status 200 and body
  • FAIL API 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-actions for create a simple reducer
  • createReducer has 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

combineReducers helps 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);
    });
  });
});