index.js 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. import { actionIsLoading } from '../../loading/action';
  2. import {
  3. actionLogInSuccess,
  4. actionLogInReject,
  5. actionLogOutSuccess,
  6. actionLogOutReject,
  7. } from '../action';
  8. import { loginGQL, registerGQL } from '../../../api-data';
  9. const asyncLogin = (login, password) => async dispatch => {
  10. try {
  11. dispatch(actionIsLoading(true));
  12. const token = await loginGQL(login, password);
  13. if (!token) throw new Error('Wrong credentials');
  14. localStorage.token = token;
  15. dispatch(actionLogInSuccess({ login, token }));
  16. } catch (e) {
  17. dispatch(actionLogInReject());
  18. } finally {
  19. dispatch(actionIsLoading(false));
  20. }
  21. };
  22. const asyncLogout = () => async dispatch => {
  23. try {
  24. dispatch(actionIsLoading(true));
  25. dispatch(actionLogOutSuccess({ login: '', token: '' }));
  26. localStorage.token = null;
  27. } catch (e) {
  28. dispatch(actionLogOutReject());
  29. } finally {
  30. dispatch(actionIsLoading(false));
  31. }
  32. };
  33. const asyncCreateUser = (login, password) => async dispatch => {
  34. try {
  35. dispatch(actionIsLoading(true));
  36. await registerGQL(login, password);
  37. const token = await loginGQL(login, password);
  38. if (!token) throw new Error('Server error');
  39. dispatch(actionLogInSuccess({ login, token }));
  40. } catch (e) {
  41. console.error('Credentials have already used', e);
  42. } finally {
  43. dispatch(actionIsLoading(false));
  44. }
  45. };
  46. export { asyncLogin, asyncLogout, asyncCreateUser };