Skip to content

Instantly share code, notes, and snippets.

@thetallweeks
Created May 6, 2019 23:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save thetallweeks/9da709fbec9c2682bc84aa4d864315e3 to your computer and use it in GitHub Desktop.
Save thetallweeks/9da709fbec9c2682bc84aa4d864315e3 to your computer and use it in GitHub Desktop.
import find from "lodash/find";
import get from "lodash/get";
import isEmpty from "lodash/isEmpty";
import api from "utils/api";
import { createSelector } from "reselect";
import {
actionTypesFor,
actionCreatorsFor,
selectorsFor,
generateInitialState,
fetchSingleStartReducer,
fetchSingleSuccessReducer,
fetchSingleFailReducer
} from "redux/utils/crud";
import { getViewSchema } from "utils/schema";
const entityName = "taskSchemas";
const options = {
fetch: true,
fetchSingle: true,
create: false,
update: false,
delete: false
};
export const actionTypes = actionTypesFor(entityName, options);
const actionCreators = actionCreatorsFor(entityName, options);
const defaultSelectors = selectorsFor(entityName, options);
const getSchema = state => get(defaultSelectors.getData(state), 0);
const getLookup = (state, lookup) => lookup;
const getByLookup = createSelector(
[defaultSelectors.getData, getLookup],
(items, lookup) => {
return find(items, lookup);
}
);
export const selectors = {
...defaultSelectors,
getSchema,
getByLookup
};
const initialState = generateInitialState({}, options);
export default function reducer(state = initialState, action = {}) {
switch (action.type) {
case actionTypes.FETCH_SINGLE_START:
return fetchSingleStartReducer(state, action);
case actionTypes.FETCH_SINGLE_SUCCESS:
return fetchSingleSuccessReducer(state, action);
case actionTypes.FETCH_SINGLE_FAIL:
return fetchSingleFailReducer(state, action);
default:
return state;
}
}
export function fetchTaskSchemas({ useCache = false } = {}) {
return (dispatch, getState) => {
if (useCache) {
const hasFetched = selectors.getHasFetched(getState());
const cached = selectors.getData(getState());
if (hasFetched && !isEmpty(cached)) {
return Promise.resolve(cached);
}
}
dispatch(actionCreators.fetchSingleStart());
return api
.get(`/schemas/generic.task?schema_type=view`)
.then(result => {
dispatch(actionCreators.fetchSingleSuccess(getViewSchema(result)));
return getViewSchema(result);
})
.catch(error => {
dispatch(actionCreators.fetchSingleFail(error));
});
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment