Created
June 7, 2017 07:59
-
-
Save kulakowka/07688b38ea26abb1df672ee92d160f36 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
export const setEntities = (entityType, entities) => ({ | |
type: 'SET_ENTITIES', | |
payload: { entities }, | |
meta: { entityType } | |
}) | |
export const removeEntities = (entityType, ids) => ({ | |
type: 'REMOVE_ENTITIES', | |
meta: { ids, entityType } | |
}) | |
export const setEntity = (entityType, entity) => ({ | |
type: 'SET_ENTITY', | |
payload: { entity }, | |
meta: { entityType } | |
}) | |
export const removeEntity = (entityType, id) => ({ | |
type: 'REMOVE_ENTITY', | |
meta: { id, entityType } | |
}) | |
///////////////////////////////////////////////////////////////////////////////////// | |
export const createEntity = (entityType, data) => ({ | |
type: 'CREATE_ENTITY', | |
payload: data, | |
meta: { entityType } | |
}) | |
export const updateEntity = (entityType, id, data) => ({ | |
type: 'UPDATE_ENTITY', | |
payload: data, | |
meta: { entityType, id } | |
}) | |
export const deleteEntity = (entityType, id) => ({ | |
type: 'DELETE_ENTITY', | |
meta: { entityType, id } | |
}) | |
//////////////////////////////////////////////////////////////////////////////////// | |
const entitiesMiddleware = store => next => action => { | |
next(action) | |
switch (action.type) { | |
case 'CREATE_ENTITY': | |
return axios | |
.post('/' + action.entityType, { form: action.payload }) | |
.then(res => next(setEntity(action.meta.entityType, res.data))) | |
case 'UPDATE_ENTITY': | |
return axios | |
.put('/' + action.meta.entityType + '/' + action.meta.id, { form: action.payload }) | |
.then(res => next(setEntity(action.meta.entityType, res.data))) | |
case 'DELETE_ENTITY': | |
return axios | |
.delete('/' + action.meta.entityType + '/' + action.meta.id) | |
.then(res => next(removeEntity(action.meta.entityType, action.meta.id))) | |
default: | |
return false | |
} | |
} | |
//////////////////////////////////////////////////////////////////////////////////// | |
setEntities('articles', [ | |
{id: 1, name: 'article 1'}, | |
{id: 2, name: 'article 2'}, | |
{id: 3, name: 'article 3'} | |
]) | |
removeEntities('articles', [1, 2, 3]) | |
setEntity('articles', {id: 1, name: 'article 1'}) | |
removeEntity('articles', 1) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment