model.ts 1.49 KB
Newer Older
陈帅's avatar
陈帅 committed
1 2
import { queryCurrent, queryFakeList } from './service';
import { CurrentUser, ListItemDataType } from './data';
3 4

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

陈帅's avatar
陈帅 committed
9 10 11 12 13 14
import { Reducer } from 'redux';
import { EffectsCommandMap } from 'dva';
import { AnyAction } from 'redux';

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

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

const Model: ModelType = {
32 33 34 35
  namespace: 'BLOCK_NAME_CAMEL_CASE',

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

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

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

export default Model;