index.ts 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. import {
  2. actionLoginSuccess,
  3. actionLoginReject,
  4. actionLogoutSuccess,
  5. actionLogoutReject,
  6. } from '../action';
  7. import { actionLoading } from '../../loading/action';
  8. import { loginGQL, registerGQL } from '../../../api-data';
  9. const asyncLogin = (login: string, password: string) => async (
  10. dispatch: any,
  11. ) => {
  12. try {
  13. dispatch(actionLoading(true));
  14. const token = await loginGQL<string>(login, password);
  15. if (!token) throw new Error('Wrong credentials');
  16. localStorage.token = token;
  17. dispatch(actionLoginSuccess({ login, token }));
  18. } catch (e) {
  19. dispatch(actionLoginReject());
  20. } finally {
  21. dispatch(actionLoading(false));
  22. }
  23. };
  24. const asyncLogout = () => async (dispatch: any) => {
  25. try {
  26. dispatch(actionLoading(true));
  27. dispatch(actionLogoutSuccess({ login: '', token: '' }));
  28. localStorage.token = null;
  29. } catch (e) {
  30. dispatch(actionLogoutReject());
  31. } finally {
  32. dispatch(actionLoading(false));
  33. }
  34. };
  35. const asyncCreateUser = (login: string, password: string) => async (
  36. dispatch: any,
  37. ) => {
  38. try {
  39. dispatch(actionLoading(true));
  40. await registerGQL(login, password);
  41. const token = await loginGQL<string>(login, password);
  42. if (!token) throw new Error('Server error');
  43. dispatch(actionLoginSuccess({ login, token }));
  44. } catch (e) {
  45. dispatch(actionLoginReject());
  46. } finally {
  47. dispatch(actionLoading(false));
  48. }
  49. };
  50. export { asyncLogin, asyncLogout, asyncCreateUser };