model.ts 2.02 KB
Newer Older
陈帅's avatar
陈帅 committed
1
import { routerRedux } from 'dva/router';
2 3
import { getPageQuery } from './utils/utils';
import { fakeAccountLogin, getFakeCaptcha } from './service';
4

陈帅's avatar
陈帅 committed
5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
import { Reducer } from 'redux';
import { EffectsCommandMap } from 'dva';
import { AnyAction } from 'redux';

export interface IStateType {
  status?: 'ok' | 'error';
  type?: string;
  currentAuthority?: 'user' | 'guest' | 'admin';
}

export type Effect = (
  action: AnyAction,
  effects: EffectsCommandMap & { select: <T>(func: (state: IStateType) => T) => T }
) => void;

export interface ModelType {
  namespace: string;
  state: IStateType;
  effects: {
    login: Effect;
    getCaptcha: Effect;
  };
  reducers: {
    changeLoginStatus: Reducer<IStateType>;
  };
}

const Model: ModelType = {
33
  namespace: 'BLOCK_NAME_CAMEL_CASE',
34 35 36 37 38 39

  state: {
    status: undefined,
  },

  effects: {
afc163's avatar
afc163 committed
40
    *login({ payload }, { call, put }) {
ddcat1115's avatar
ddcat1115 committed
41
      const response = yield call(fakeAccountLogin, payload);
42
      yield put({
43
        type: 'changeLoginStatus',
44 45
        payload: response,
      });
afc163's avatar
afc163 committed
46 47
      // Login successfully
      if (response.status === 'ok') {
48
        const urlParams = new URL(window.location.href);
yoyo837's avatar
yoyo837 committed
49
        const params = getPageQuery();
陈帅's avatar
陈帅 committed
50
        let { redirect } = params as { redirect: string };
51 52 53 54
        if (redirect) {
          const redirectUrlParams = new URL(redirect);
          if (redirectUrlParams.origin === urlParams.origin) {
            redirect = redirect.substr(urlParams.origin.length);
55
            if (redirect.match(/^\/.*#/)) {
xiaoiver's avatar
xiaoiver committed
56
              redirect = redirect.substr(redirect.indexOf('#') + 1);
yoyo837's avatar
yoyo837 committed
57
            }
58 59 60 61 62
          } else {
            window.location.href = redirect;
            return;
          }
        }
63
        yield put(routerRedux.replace(redirect || '/'));
64
      }
ddcat1115's avatar
fix #52  
ddcat1115 committed
65
    },
陈帅's avatar
陈帅 committed
66

67 68 69
    *getCaptcha({ payload }, { call }) {
      yield call(getFakeCaptcha, payload);
    },
70 71 72
  },

  reducers: {
73
    changeLoginStatus(state, { payload }) {
74 75 76 77 78 79 80 81
      return {
        ...state,
        status: payload.status,
        type: payload.type,
      };
    },
  },
};
陈帅's avatar
陈帅 committed
82 83

export default Model;