model.ts 1.49 KB
Newer Older
陈帅's avatar
陈帅 committed
1
import { AnyAction, Reducer } from 'redux';
陈帅's avatar
陈帅 committed
2
import { EffectsCommandMap } from 'dva';
陈帅's avatar
陈帅 committed
3
import { CurrentUser, ListItemDataType } from './data.d';
陈帅's avatar
陈帅 committed
4
import { queryCurrent, queryFakeList } from './service';
5 6

export interface ModalState {
陈帅's avatar
陈帅 committed
7
  currentUser: Partial<CurrentUser>;
陈帅's avatar
陈帅 committed
8
  list: ListItemDataType[];
9 10
}

陈帅's avatar
陈帅 committed
11 12
export type Effect = (
  action: AnyAction,
陈帅's avatar
陈帅 committed
13
  effects: EffectsCommandMap & { select: <T>(func: (state: ModalState) => T) => T },
陈帅's avatar
陈帅 committed
14 15 16 17 18 19 20
) => void;

export interface ModelType {
  namespace: string;
  state: ModalState;
  effects: {
    fetchCurrent: Effect;
陈帅's avatar
陈帅 committed
21
    fetch: Effect;
陈帅's avatar
陈帅 committed
22 23 24
  };
  reducers: {
    saveCurrentUser: Reducer<ModalState>;
陈帅's avatar
陈帅 committed
25
    queryList: Reducer<ModalState>;
陈帅's avatar
陈帅 committed
26 27 28 29
  };
}

const Model: ModelType = {
30 31 32 33
  namespace: 'BLOCK_NAME_CAMEL_CASE',

  state: {
    currentUser: {},
陈帅's avatar
陈帅 committed
34
    list: [],
35 36 37
  },

  effects: {
陈帅's avatar
陈帅 committed
38
    *fetchCurrent(_, { call, put }) {
39 40 41 42 43 44
      const response = yield call(queryCurrent);
      yield put({
        type: 'saveCurrentUser',
        payload: response,
      });
    },
陈帅's avatar
陈帅 committed
45 46 47 48 49 50 51
    *fetch({ payload }, { call, put }) {
      const response = yield call(queryFakeList, payload);
      yield put({
        type: 'queryList',
        payload: Array.isArray(response) ? response : [],
      });
    },
52 53 54
  },

  reducers: {
陈帅's avatar
陈帅 committed
55
    saveCurrentUser(state, action) {
56
      return {
陈帅's avatar
陈帅 committed
57
        ...(state as ModalState),
58 59 60
        currentUser: action.payload || {},
      };
    },
陈帅's avatar
陈帅 committed
61 62
    queryList(state, action) {
      return {
陈帅's avatar
陈帅 committed
63
        ...(state as ModalState),
陈帅's avatar
陈帅 committed
64 65 66
        list: action.payload,
      };
    },
67 68
  },
};
陈帅's avatar
陈帅 committed
69 70

export default Model;