Skip to content

Instantly share code, notes, and snippets.

@thetallweeks
Created May 6, 2019 23:12
Show Gist options
  • Select an option

  • Save thetallweeks/9da709fbec9c2682bc84aa4d864315e3 to your computer and use it in GitHub Desktop.

Select an option

Save thetallweeks/9da709fbec9c2682bc84aa4d864315e3 to your computer and use it in GitHub Desktop.

Revisions

  1. Kevin Weeks created this gist May 6, 2019.
    87 changes: 87 additions & 0 deletions schema.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,87 @@
    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));
    });
    };
    }