thetallweeks
5/6/2019 - 11:12 PM

Task Schemas

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