redux: auth and map init

This commit is contained in:
muerwre 2018-11-26 11:56:19 +07:00
parent dca55a3bc4
commit df6202c32d
17 changed files with 325 additions and 163 deletions

View file

@ -0,0 +1,4 @@
import { ACTIONS } from '$redux/user/constants';
export const setUser = user => ({ type: ACTIONS.SET_USER, user });
export const setEditing = editing => ({ type: ACTIONS.SET_EDITING, editing });

View file

@ -0,0 +1,4 @@
export const ACTIONS = {
SET_USER: 'SET_USER',
SET_EDITING: 'SET_EDITING',
};

25
src/redux/user/reducer.js Normal file
View file

@ -0,0 +1,25 @@
import { createReducer } from 'reduxsauce';
import { ACTIONS, EMPTY_USER } from '$redux/user/constants';
import { DEFAULT_USER } from '$constants/auth';
const setUser = (state, { user }) => ({
...state,
...user,
});
const setEditing = (state, { editing }) => ({
...state,
editing,
});
const HANDLERS = {
[ACTIONS.SET_USER]: setUser,
[ACTIONS.SET_EDITING]: setEditing,
};
export const INITIAL_STATE = {
...DEFAULT_USER
};
export const userReducer = createReducer(INITIAL_STATE, HANDLERS);

80
src/redux/user/sagas.js Normal file
View file

@ -0,0 +1,80 @@
import { REHYDRATE } from 'redux-persist';
import { takeLatest, select, call, put } from 'redux-saga/effects';
import { checkUserToken, getGuestToken, getStoredMap } from '$utils/api';
import { setUser } from '$redux/user/actions';
import { getUrlData, pushPath } from '$utils/history';
import { editor } from '$modules/Editor';
const getUser = state => (state.user);
const hideLoader = () => {
document.getElementById('loader').style.opacity = 0;
document.getElementById('loader').style.pointerEvents = 'none';
return true;
};
function* generateGuestSaga() {
const user = yield call(getGuestToken);
yield put(setUser(user));
return user;
}
function* startEmptyEditorSaga() {
const { id, random_url } = yield select(getUser);
console.log('RURL', random_url);
pushPath(`/${random_url}/edit`);
editor.owner = id;
editor.startEditing();
return hideLoader();
// todo: this.clearChanged();
}
function* mapInitSaga() {
const { path, mode } = getUrlData();
if (path) {
const map = yield call(getStoredMap, { name: path });
if (map) {
// todo: this.clearChanged();
editor.setData(map);
if (mode && mode === 'edit') {
editor.startEditing();
} else {
editor.stopEditing();
}
return hideLoader();
}
}
return yield call(startEmptyEditorSaga);
}
function* authChechSaga() {
const { id, token } = yield select(getUser);
if (id && token) {
const user = yield call(checkUserToken, { id, token });
if (user && user.success) {
yield put(setUser(user));
return yield call(mapInitSaga);
}
}
yield call(generateGuestSaga);
return yield call(mapInitSaga);
}
export function* userSaga() {
// Login
// yield takeLatest(AUTH_ACTIONS.SEND_LOGIN_REQUEST, sendLoginRequestSaga);
yield takeLatest(REHYDRATE, authChechSaga);
}