accounts-frontend/src/components/user/actions.ts

118 lines
2.4 KiB
TypeScript
Raw Normal View History

import {
getInfo as getInfoEndpoint,
changeLang as changeLangEndpoint,
acceptRules as acceptRulesEndpoint,
2019-12-07 16:58:52 +05:30
UserResponse,
} from 'services/api/accounts';
2016-05-20 01:11:43 +05:30
import { setLocale } from 'components/i18n/actions';
2019-12-07 16:58:52 +05:30
import { ThunkAction } from 'reducers';
2016-02-26 11:55:47 +05:30
2019-12-07 16:58:52 +05:30
import { User } from './reducer';
export const UPDATE = 'USER_UPDATE';
/**
2016-11-05 15:41:41 +05:30
* Merge data into user's state
*
* @param {object} payload
* @returns {object} - action definition
*/
2019-12-07 16:58:52 +05:30
export function updateUser(payload: Partial<User>) {
// Temp workaround
return {
type: UPDATE,
payload,
};
}
export const SET = 'USER_SET';
/**
* Replace current user's state with a new one
*
* @param {User} payload
* @returns {object} - action definition
*/
2019-12-07 16:58:52 +05:30
export function setUser(payload: Partial<User>) {
return {
type: SET,
payload,
};
}
2016-05-20 01:11:43 +05:30
export const CHANGE_LANG = 'USER_CHANGE_LANG';
2019-12-07 16:58:52 +05:30
export function changeLang(lang: string): ThunkAction<Promise<void>> {
return (dispatch, getState) =>
dispatch(setLocale(lang)).then((lang: string) => {
const { id, isGuest, lang: oldLang } = getState().user;
2019-11-11 14:10:05 +05:30
if (oldLang === lang) {
return;
}
2016-05-20 01:11:43 +05:30
if (!isGuest && id) {
changeLangEndpoint(id, lang);
}
dispatch({
type: CHANGE_LANG,
payload: {
lang,
},
});
});
2016-05-20 01:11:43 +05:30
}
2019-12-07 16:58:52 +05:30
export function setGuest(): ThunkAction<Promise<void>> {
return async (dispatch, getState) => {
dispatch(
setUser({
lang: getState().user.lang,
isGuest: true,
}),
);
};
}
2016-02-26 11:55:47 +05:30
2019-12-07 16:58:52 +05:30
export function fetchUserData(): ThunkAction<Promise<UserResponse>> {
return async (dispatch, getState) => {
const { id } = getState().user;
if (!id) {
throw new Error('Can not fetch user data. No user.id available');
}
const resp = await getInfoEndpoint(id);
dispatch(
updateUser({
isGuest: false,
...resp,
}),
);
dispatch(changeLang(resp.lang));
2016-05-20 01:11:43 +05:30
return resp;
};
2016-02-26 11:55:47 +05:30
}
2019-12-07 16:58:52 +05:30
export function acceptRules(): ThunkAction<Promise<{ success: boolean }>> {
return (dispatch, getState) => {
const { id } = getState().user;
if (!id) {
throw new Error(
'user id is should be set at the moment when this action is called',
);
}
2016-08-03 00:29:29 +05:30
return acceptRulesEndpoint(id).then(resp => {
dispatch(
updateUser({
shouldAcceptRules: false,
}),
);
return resp;
});
};
}