model.ts 2.08 KB
Newer Older
陈帅's avatar
陈帅 committed
1
import { routerRedux } from 'dva/router';
陈帅's avatar
陈帅 committed
2
import { getPageQuery, setAuthority } from './utils/utils';
3
import { fakeAccountLogin, getFakeCaptcha } from './service';
陈帅's avatar
陈帅 committed
4 5 6 7 8 9 10 11 12 13 14 15
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,
陈帅's avatar
陈帅 committed
16
  effects: EffectsCommandMap & { select: <T>(func: (state: IStateType) => T) => T },
陈帅's avatar
陈帅 committed
17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
) => void;

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

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

  state: {
    status: undefined,
  },

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

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

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

export default Model;