89 lines
2.1 KiB
TypeScript
Raw Normal View History

2020-05-24 02:08:24 +03:00
import { changeLang as changeLangEndpoint, acceptRules as acceptRulesEndpoint } from 'app/services/api/accounts';
import { setLocale } from 'app/components/i18n/actions';
import { ThunkAction } from 'app/reducers';
2016-02-26 08:25:47 +02:00
2019-12-07 13:28:52 +02:00
import { User } from './reducer';
export const UPDATE = 'USER_UPDATE';
/**
2016-11-05 12:11:41 +02:00
* Merge data into user's state
*
* @param {object} payload
* @returns {object} - action definition
*/
2019-12-07 13:28:52 +02:00
export function updateUser(payload: Partial<User>) {
2020-05-24 02:08:24 +03:00
// 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 13:28:52 +02:00
export function setUser(payload: Partial<User>) {
2020-05-24 02:08:24 +03:00
return {
type: SET,
payload,
};
}
2016-05-19 22:41:43 +03:00
export const CHANGE_LANG = 'USER_CHANGE_LANG';
export function changeLang(targetLang: string): ThunkAction<Promise<void>> {
2020-05-24 02:08:24 +03:00
return async (dispatch, getState) =>
dispatch(setLocale(targetLang)).then((lang: string) => {
const { id, isGuest, lang: oldLang } = getState().user;
2019-11-11 10:40:05 +02:00
2020-05-24 02:08:24 +03:00
if (oldLang === lang) {
return;
}
2016-05-19 22:41:43 +03:00
2020-05-24 02:08:24 +03:00
if (!isGuest && id) {
changeLangEndpoint(id, lang);
}
2020-05-24 02:08:24 +03:00
dispatch({
type: CHANGE_LANG,
payload: {
lang,
},
});
});
2016-05-19 22:41:43 +03:00
}
2019-12-07 13:28:52 +02:00
export function setGuest(): ThunkAction<Promise<void>> {
2020-05-24 02:08:24 +03:00
return async (dispatch, getState) => {
dispatch(
setUser({
lang: getState().user.lang,
isGuest: true,
}),
);
};
}
2016-02-26 08:25:47 +02:00
2019-12-07 13:28:52 +02:00
export function acceptRules(): ThunkAction<Promise<{ success: boolean }>> {
2020-05-24 02:08:24 +03:00
return (dispatch, getState) => {
const { id } = getState().user;
2020-05-24 02:08:24 +03:00
if (!id) {
throw new Error('user id is should be set at the moment when this action is called');
}
2016-08-02 21:59:29 +03:00
2020-05-24 02:08:24 +03:00
return acceptRulesEndpoint(id).then((resp) => {
dispatch(
updateUser({
shouldAcceptRules: false,
}),
);
2020-05-24 02:08:24 +03:00
return resp;
});
};
}